Search code examples
phplaravelmany-to-many

Passing array in many to many relationship to the controller- laravel


I have a many to many relationship between Category and posts tables like this:

Category class:

class Category extends Model {
public function posts()
    {
    //return $this->hasMany('App\Posts','category_id');
    return $this->belongsToMany('App\Posts', 'categories_post', 'category_id', 'post_id')
    ->withTimestamps();
    }
}

Posts class:

class Posts extends Model {
   public function category()
   {
    //return $this->belongsTo('App\Category','category_id');
    return $this->belongsToMany('App\Category', 'categories_post', 'post_id', 'category_id')
    ->withTimestamps();
   }
}

When I need to access only one category's posts I do this in my controller:

    public function cat($category_id)
{
$posts= $category_id->posts()->paginate(7);
return view('cat')->with('posts',$posts);
}

Edit

to make this work, I added this in "RouteServiceProvider.php" file:

    public function boot(Router $router)
{
    parent::boot($router);
    $router->model('categories','App\Category');
}

and this works perfectly. The problem is, I have another controller which should get the posts for multiple categories :

    public function index()
{
    $title = 'news';
    $categories= [1, 2, 10, 11];
    // Here is the problem:
    $posts= $categories->posts()->paginate(7);
    return view('news')->with('posts',$posts)->with('title',$title);
}

This gives me this error: Call to a member function posts() on a non-object

I know there is something wrong with calling the array, but I don't know how to solve it. Can any one help me please :)


The solution

after what Thomas Van der Veen said in his answer , I came up with this controller which is working perfectly:

    public function index()
{
    $title = 'news';
    $category_ids = [1, 2, 10, 11];
    $posts = Posts::whereHas('category', function($query) use ($category_ids) {
$query->whereIn('id', $category_ids);
    })->get();
    return view('news')->with('posts',$posts)->with('title',$title);
}

Solution

  • You could do something like:

    $category_ids = [1, 2, 10, 11];
    
    $posts = Post::whereHas('categories', function($query) use ($category_ids) {
    
        $query->whereIn('id', $category_ids);
    
    });
    

    See this.