Support the ongoing development of Laravel.io →
Database Eloquent

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?

Last updated 2 years ago.
0

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();
Last updated 2 years ago.
0

Thanks so much for the reply - will test it tomorrow and report back!

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

azcoppen azcoppen Joined 15 Mar 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.