I have a situation where a user can upload profile photos to an album: there is a "users" table, and an images table. In the User model, there is a photos() function like so:
public function photos() {
return $this->hasMany('Photo');
}
Which i can access by Auth::user()->photos as a dynamic property.
However, only 1 photo can be marked as "default" with a field called "default" (0/1), and all the others are set to 0.
That's great, but when i call/eager-load the dynamic property, i want to be able to just pull their default photo, like so:
Auth::user()->photos->where('default', '1'); // or
Auth::user()->other_records->orderBy('created_at', 'DESC')
I can't find anywhere in the documentation that seems to do this without calling the function directly (e.g. ->photos() instead of just ->photos). Is there a way to restrict/filter dynamic properties?
You can define several methods for one relation filtered as you like, for example:
public function photos() {
return $this->hasMany('Photo');
}
public function photosDefault() {
return $this->hasMany('Photo')->where('default','1');
}
public function photosRecent() {
return $this->hasMany('Photo')->where('created_at', '>', Carbon\Carbon::now()->subWeek()->toDateTimeString();
}
Otherwise use photos()->...->get() as it returns Relation object not Eloquent Model/Collection so you can chain it.
And by the way you can easily do it on the fly when eager loading the model:
User::with(['photos' => function ($query) {
$query->where('default', '1');
}])->get();
Thanks so much for the reply - will test it tomorrow and report back!
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community