Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 weeks 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 weeks ago.
0

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

Last updated 2 weeks ago.
0

Sign in to participate in this thread!

Full Stack Europe

Your banner here too?

azcoppen azcoppen azcoppen Joined 15 Mar 2014

Moderators

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

Your logo here?

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

© 2022 Laravel.io - All rights reserved.