Started learning Laravel recently and came across a bit of code which caused me some headaches and need an explanation as to why that is so.
Namely, I setup a basic laravel app, in my User
model (standard model class) I created a method as such:
public function projects() {
return $this->hasMany(Project::class, 'project_owner_id');
}
Simple enough, I have a Project
model, it has it's own table, which has a column and foreign key of project_owner_id
and I am just referencing the relationship between the two models.
Now in my controller when I try to access that method and fetch all the projects which belong to the logged in user as following, I get an error:
$projects = auth()->user()->projects();
It took me some amount of time to realise that the error was caused by me when calling the projects
as a function and not a property, once i refactored the code as such:
$projects = auth()->user()->projects;
all was well and working correctly, i was getting the projects which belonged to the logged in user.
My questions is: can someone explain as to why that is, why didn't it work when i tried calling the projects
method as a function?
Eloquent relationships are defined as methods on your Eloquent model classes.
public function projects() {
return $this->hasMany(Project::class, 'project_owner_id');
}
Once the relationship is defined, we may retrieve the related record using Eloquent's dynamic properties. Dynamic properties allow you to access relationship methods as if they were properties defined on the model:
auth()->user()->projects;
Defining relationships as methods provides powerful method chaining and querying capabilities.For example, we may chain additional constraints on this projects relationship:
auth()->user()->projects()->where("status", 1)->get();