Reputation: 11
I am a beginner in laravel and developing a blog website. What is the most convenient way to make blog titles links which will direct the user to the blog itself.
Upvotes: 0
Views: 995
Reputation: 1349
For each of your blog posts, beside having a title, create another column slug
, and when you are storing a blog post, slugify and store it too. Then you can use it in your queries and route variables.
steps:
in your migration add the slug
$table->string('slug')->unique();
Put this inside your model, this will automatically slugify the title when you are storing the model.
use Illuminate\Support\Str;
public static function boot()
{
parent::boot();
self::creating(function($model){
$model->slug = Str::slug($model->title, '-');
});
}
Then in your blog post accessing route:
Route::get('/posts/{slug_title}', 'PostController@show')->name('posts.show');
And finally inside your controller/action:
public function show($slug_title)
{
$post = Post::query()
->where('slug', $slug_title)
->first();
return $post;
}
Upvotes: 2