How can i get a limited items from relationship with Laravel
this is my laravel code:
$data = $category->posts;
i want something like:
$data = $category->posts->limit(4);
How can i get a limited items from relationship with Laravel
this is my laravel code:
$data = $category->posts;
i want something like:
$data = $category->posts->limit(4);
Accessing a relationship like a method (i.e. $category->posts()
) will give you a query builder, on which you can chain methods:
$firstFourPosts = $category->posts()->take(4)->get();
Define a separate relationship with the limit (or change posts()
):
public function postsLimited() {
return $this->posts()->limit(4);
}
$data = $category->postsLimited;