How does the Article factory know to grab the id column from the newly generated users for the user_id in the new article data? I don't see anything explicitly telling it to do so. Is it just by default grabbing data from the first column? Or since it's referencing the newly created Users does it just know to use the default id column because it hasn't been told otherwise?
Stuff like this is often overlooked in tutorials, but I feel like knowing it will help me when I'm creating my own sites.
You can always use the method getKey() on a model to get it's primary key, this is also what the factory is doing, you can see the code for this in the method expandAttributes in Illuminate\Database\Eloquent\FactoryBuilder.
Inside this method you will find these lines (among others):
if ($attribute instanceof static) {
$attribute = $attribute->create()->getKey();
}
if ($attribute instanceof Model) {
$attribute = $attribute->getKey();
}
It checks if the $attribute is a FactoryBuilder (instance of static) or a Model, in both cases it ends up calling the getKey() method on the model. In your specific example the first if case will be used.
If you want to find out how getKey works in detail i suggest you look at that method in Illuminate\Database\Eloquent\Model, there you can see how it figures out what the primary key is.
Thank you. I didn't think to check the code inside of my Laravel project. I'll start seeking the definitions of stuff and see what I find before posting questions.