0

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);
Ghyath Darwish
  • 2,178
  • 4
  • 11
  • 28

2 Answers2

2

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();
Martin Bean
  • 36,612
  • 23
  • 119
  • 192
  • yes it solved my problem, but i want to get another relation ship from `$firstFourPosts` i was use `$data = $category->posts;` `$data->comments` but now with your code it is no longer work. sorry about my English – Ghyath Darwish Jul 19 '18 at 10:11
1

Define a separate relationship with the limit (or change posts()):

public function postsLimited() {
    return $this->posts()->limit(4);
}

$data = $category->postsLimited;
Jonas Staudenmeir
  • 23,013
  • 4
  • 50
  • 94