0

Been using Faker in combination with sqLite in-memory database for testing in Laravel lately and I have this strange issue where my model has a factory and everything except the first variable (which happens to also be the primary key of the table) gets set correctly.

Let's explain further, the variable I'm pointing at uses the following rule in the factory:

'kvk' => strval($faker->randomNumber(9)),

So it should become a string containing a 9 digit number. Now the next step is calling the factory from my controller test and I also have another User model which uses this 'kvk' variable from my company as a foreign key reference:

$this->_company = factory(Company::class)->create([ 'address_id' => $this->_address->id ]); 
$this->_user = factory(User::class)->create([ 'kvk' => $this->_company->kvk ]); 

But when I put an echo $this->_company->kvk; in between, it shows me that 'kvk is set to 1, which should not be possible because of the rule I put in my factory.

Finally the user is used to mock the session in the test and is also used to check wether I should have the rights to edit an address using the following check:

$user = Auth::user(); 
$company = Company::where('kvk', $user->kvk)->first(); 
$address = Address::whereId($id)->first();

if($company->address_id != $address->id)
{ 
    return abort(403); 
} 

So first I get the current logged in user (which is mocked to the created user above, and this works perfectly. Next I get the company associated with this user (which should be the one created above, since I used the company->kvk as a foreign key reference), however when I output the saved Company to my log I see that the kvk is set to a 9 digit string like it's supposed to.

I really can't put my finger on why at first the kvk is set to 1 and afterwards in my test it seems perfectly fine the way it should be, but my test fails because the wrong reference is set in my User so it can't find the right Company. Do you have any idea what could be the reason for this? I've also tried setting the 'kvk' explicitly while creating with the factory, but this also does not work and will stil output 1.

Kevin Wareman
  • 146
  • 1
  • 7

1 Answers1

0

After diving into the source of Laravel, I found out it had to with my models. While I did set the primary key attribute in my models, I forgot to set the auto increment boolean to false. This caused my models to cast the primary key to an auto increment integer every time it was saved to the database. This solved the issue.

Kevin Wareman
  • 146
  • 1
  • 7