You can use Route Model Binding to ensure that routes will find your model based on the provided key.
Your Post
model will require that you add the following method:
public function getRouteKeyName()
{
return 'slug';
}
Then, in your routes, you can just refer the model directly, and binding will happen automatically:
public function post(App\Post $post)
{
$comments = Comment::where('post_id',$post->id)->get();
return view('content.post',compact('post','comments'));
}
This enables you to to use the following route:
Route::get('post/{post}', 'PagesController@post')->name('post.show');
Now, additionally, to ease up your reference of the comments, add them as relations to your Post
model:
public function comments()
{
return $this->hasMany(Comment::class);
}
and your Comment
model:
public function post()
{
return $this->belongsTo(Post::class);
}
This will allow you to shorten your controller method even more:
public function post(App\Post $post)
{
return view('content.post',compact('post'));
}
and in your Blade view do the following instead:
@foreach($post->comments as $comment)
From: {{ $comment->name }} blah blha
@endforeach