1

I'm new in laravel. I need to have in my homepageBlog fetch 3 posts for each categories and just show 4 categories.

I'm doing in my HomeController

  $categories = Category::with(['posts' => function($query){
      $query->orderBy('published_at', 'DESC')->take(3)->get();
  }])->take(4)->get();

In my model

//post models
     public function category(){
    return $this->belongsToMany('Category', 'post_categories', 'post_id', 'category_id');
    }

in my category model

    public function posts(){
       return $this->hasMany('Post');
   }

But when I'm going in my view it's just showing 3 latest post only for 1 category and show 1 post for another.

toesslab
  • 5,092
  • 8
  • 43
  • 62
nicolassiuol
  • 83
  • 2
  • 12

1 Answers1

1

The code for your controller:

// declare a variable and an array
$catid = null;
$posts = [];

// get four categories
$categories = Category::take(4)->get();

foreach($categories as $category){
  //foreach of the four categories, get the category id
  $catid = $category->category_id;

  //add three posts of each of those categories to the $posts array
  $posts[] = Category::where('category_id', $catid)->take(3)->get();

}

Your $posts array should have everything you need.

JGCW
  • 1,509
  • 1
  • 13
  • 25
  • i have no pivot table only in post a foreign key category_id so when i do myforeach($categories as $category){ //foreach of the four categories, get the category id $category_id = $category->$category_id; //add three posts of each of those categories to the $posts array $posts[] = Category::where('category_id', $category_id)->take(3)->get(); }i have a error message Undefined variable: category_id – nicolassiuol Dec 07 '15 at 13:57
  • And for Category::find(4) return only my Category id number 5 not return 4 categories – nicolassiuol Dec 07 '15 at 14:49
  • Undefined variable: category_id i don't understand why i have this problem – nicolassiuol Dec 08 '15 at 08:06
  • do you still have this problem? – JGCW Dec 08 '15 at 08:15
  • yes i have the problem of category_id undefined i don't know why – nicolassiuol Dec 08 '15 at 08:18
  • did you declare the variable as mentioned? $category_id; ? – JGCW Dec 08 '15 at 08:19
  • yes i have decared $categoryid like in the upper answer – nicolassiuol Dec 08 '15 at 08:20
  • try declaring it in the for loop; foreach($categories as $category){ $category_id; } – JGCW Dec 08 '15 at 08:21
  • Ok i try it And coming after to say if it's ok – nicolassiuol Dec 08 '15 at 08:24
  • true, adding the declaring the variable inside the for loop will not work but i think it should be working when you declare the $category_id as a global variable. i made some changes in the code. check if it works – JGCW Dec 08 '15 at 09:09