Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading