php - Passing array in many to many relationship to the controller- laravel -
i have many many relationship between category , posts tables 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 need access 1 category's posts in controller:
public function cat($category_id) { $posts= $category_id->posts()->paginate(7); return view('cat')->with('posts',$posts); }
edit
to make work, added in "routeserviceprovider.php" file:
public function boot(router $router) { parent::boot($router); $router->model('categories','app\category'); }
and works perfectly. problem is, i have controller should posts multiple categories :
public function index() { $title = 'news'; $categories= [1, 2, 10, 11]; // here problem: $posts= $categories->posts()->paginate(7); return view('news')->with('posts',$posts)->with('title',$title); }
this gives me error: call member function posts() on non-object
i know there wrong calling array, don't know how solve it. can 1 me please :)
the solution
after thomas van der veen said in answer , came controller 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); }
you like:
$category_ids = [1, 2, 10, 11]; $posts = post::wherehas('categories', function($query) use ($category_ids) { $query->wherein('id', $category_ids); });
see this.
Comments
Post a Comment