How to limit query after with() method in laravel?

by arnoldo.moen , in category: PHP Frameworks , 9 months ago

How to limit query after with() method in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by ryleigh , 6 months ago

@arnoldo.moen 

In Laravel, you can limit the number of related records returned after using the with() method by using the take() method on the relationship.


For example, if you want to limit the number of comments related to a post to 5, you can do the following:

1
2
3
4
$post = Post::with(['comments' => function ($query) {
    $query->take(5);
}])->find(1);


In this example, take(5) limits the number of comments returned to 5 for each post. You can adjust the number in the take() method to limit the query results as needed.

Related Threads:

How to set limit in mongodb query?
What does 'as' method do in laravel?
How to use offset & limit in laravel?
What boot() method do in laravel?
How to override method in laravel?
How to limit the number of notifications in laravel?