How to show or display related posts based on category in laravel
- Post by: Public
- on: 23-02-20
Suppose i have two table one is posts and another is categories. Now i want to show related posts by using category in laravel.
At first we need to make a relation both Category and Post model.
In Category model we use: hasMany relation in Category.php
public function posts(){
return $this->hasMany('App\Post');
}
In Post model we use: belongsTo in Post.php
public function category(){
return $this->belongsTo('App\Category');
}
For showing data we need create route and controller: suppose i have create a
BlogController.php and make a route as blew
#web.php
Route::get('/post/{slug}', [
'uses' => 'BlogController@show',
'as' => 'post.single'
]);
# BlogController.php
public function show($slug){
$post=Post::where('slug',$slug)->first();
$categories=Category::all();
$related= Post::where('category_id', '=', $post->category->id)->where('id', '!=', $post->id)->get();
return view('post.single')->with('post',$post)
->withCategories($categories)
->withRelated($related);
}
Now we will show or display related post in view blade
#single.blade.php
@if(empty($related))
<p style="color:red;"> Sorry ! No Related Post Found.</p>
@else
<div class="related-posts section-title">
<h2><span>Related Posts</span></h2>
<div class="row">
@foreach($related->take(6) as $relate)
<div class="col-md-4">
<a class="related-items" href="{{route('post.single',['slug' =>$relate->slug])}}">
<img src="/storage/{{$relate->image}}" class="img-thumbnail" alt="{{$relate->title}}"/>
</a>
</div>
@endforeach
</div>
</div> <!--related-posts-->
@endif
It will show related product on running category posts. In that way you can show related post or product by laravel
Thanks for reads our blog please share with your friends & family who love to learn php laravel.
Comments