Reputation: 1373
I have a blog list. When I click on a blog I want to make the URL as the blog name like : www.domain.com/blog/my-blog-name
.
In my blog list I have the link as blog/blogid(2/3/4) ex : www.domain.com/blog/1
When someone visit www.domain.com/blog/1
then the URL should be www.domain.com/blog/my-blog-name
{ the blog name will change as per the blog Id }
I did so many research on this but no luck. It would be great if anyone help me to get out of this.
I am using laravel 5.4. I am new to laravel also.
Upvotes: 2
Views: 12013
Reputation: 147
You can just override the function getRouteKeyName
public function getRouteKeyName()
{
return 'slug';
}
Upvotes: 1
Reputation: 429
You can use Laravel mutators setSlugAttribute in your model:
public function setSlugAttribute($title){
$this->attributes['slug'] = str_replace(' ','-',$title);
}
and write this sample code in your web.php :
Route::get('/blog/{slug}', 'BlogController@show');
You can use slug in your method.
public function findBySlug($slug){
$post = Post::whereSlug($slug)->firstOrFail();
}
Upvotes: 0
Reputation: 838
You can create a unique slug or name for your blog , but since names can be duplicate and for the user it is difficult to manually create a unique slug, then I would advise you to do so
Route::get('/blog/{id}/{name}', 'BlogController@show');
this it will look nice in url, as here for example in stackoverflow!
Upvotes: 2
Reputation: 332
You need to create a slug
field in your database and you will find
a post using slug
instead of id
Define route:
Route::get('post/{slug}', 'PostsControler@findBySlug');
Example http://example.com/post/my-awesome-blog-post
and in your controller
//PostsController.php
public function findBySlug($slug)
{
$post = Post::where('slug', $slug)->firstOrFail();
// return view
}
I suggest you use Eloquent-Sluggable to auto create slug
value from your title
field
$post = new Post([
'title' => 'My Awesome Blog Post',
]);
$post->save();
// $post->slug is "my-awesome-blog-post"
Upvotes: 4
Reputation: 915
you can simply take your title from database and use it as a slug like below :
$slug = str_replace(' ','-',$yourtitle);
Upvotes: 0
Reputation: 5041
Try with following one!
In your routes
file:
Route::get('blog/{slug}', 'BlogController@show'); // make sure not conflict with resource routes define
And then your BlogController
:
public function show($slug)
{
$id = explode($slug, '-')[0]; //get id of post
// your logic
}
Hope this helps you!
Upvotes: 0