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


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 = [
        '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 = [

    public function __construct() {

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

Or you could do it whenever you do the query.

        'lawyer' => function ($query) { $query->limit(4); },

Leave a ReplyCancel reply