0

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.

1
  • Slugs, so you can navigate to website/blog/cool-blog-title instead of website/blogs/1, but you'll have to figure out a way to implement that. Commented Jul 14, 2021 at 18:39

1 Answer 1

2

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; 
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, this has opened up my mind.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.