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,614
  • 4
  • 15
  • 31

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
  • 38,379
  • 25
  • 128
  • 201
  • 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
  • 24,815
  • 6
  • 63
  • 109