How to add 'limit()' to $with in laravel's model?

Advertisements

I want to add an eager load to my model, however – I want to limit the related records.
I know how to do it using the load(Model::class)->limit(n) and also in the relationship method, like this: $this->belongsTo(User::class)->limit(n)

My problem it that I need to do it in the $with property. I tried many options, none worked (all failed as a code error).

My best guess is:

protected $with = [
        'user:id,display_name',
        'lawyer' => fn ($query) => $query->limit(4)
    ];

>Solution :

PHP cannot declare properties with dynamic values. You can either set the with property on the construction of the object.

class YourModel extends Model
{
    protected $with = [
        'user:id,display_name',
    ];

    public function __construct() {
        parent::__construct();

        $this->with['lawyer'] = function ($query) { $query->limit(4); };
    }
}

Or you could do it whenever you do the query.

YourModel::with(
    [
        'lawyer' => function ($query) { $query->limit(4); },
    ]
)->get();

Leave a ReplyCancel reply