I have a website where I post recipes. each of them has a category, and I want to display 2-3 more messages with the same category of this message. How can I create a query to display it? I have a Post Model and Category model, which has toMany relationship between them and populates a pivot table that I bind these categories to the message.
This is a function in my BController, it is a function that passes data to views in which users can access and view.
public function slug(Request $request, $slug)
{
if (Auth::check()) {
$fav = DB::table('post_user')->whereUserId(Auth::id())->pluck('post_id')->all();
}
$query=$request->get('q');
if ($query) {
$posts = $query ? Post::search($query)
->orderBy('id','desc')
->paginate(7) : Post::all();
return view('home', compact('posts','fav'));
}
else {
$url = $request->url();
$post = Post::where('slug', '=', $slug)->first();
return view('b.s', compact('post','url'));
}
}
this is my publication model:
public function categories(){
return $this->belongsToMany('App\Category');
}
This is in Category Category:
public function posts(){
return $this->belongsToMany('App\Post');
}
The summary table looks like this:
$table->increments('id');
$table->integer('post_id')->unsigned();
$table->foreign('post_id')->references('id')
->on('posts')->onDelete('cascade');
$table->integer('category_id')->unsigned()->nullable();
$table->foreign('category_id')->references('id')
->on('categories')->onDelete('cascade');