Reputation: 467
I'm creating a blog post with Laravel 5.5. Here I want to auto-generate accessible slug for a post upon saving. What I did here was:
'slug' => str_slug(request('title'))
It generates the slug value but the page url is not working. For e.g if I click 127.0.0.1:8000/title
it should redirect me.
Controller
public function save(Request $request, Post $post)
{
$post= new Post;
$post->title = request('title');
$post->slig => str_slug(request('title'));
$post->save();
}
Route
Route::post('/', 'PostsController@save')->name('add_post');
Upvotes: 1
Views: 3239
Reputation: 99
we store the title and replace every space to dash '-' to auto-generate accessible slug for a post upon saving on this steps :
i use this code on controller
public function store(Request $request){$post->slug = str_replace(' ','-',strtolower($post->title));}
and on
public function show($slug)
{
//
$post=Post::where('slug',$slug)->first();
return view('posts.show', compact('post'));
}
and edit post link like this
<a href="/posts/{{$post->slug}}">link</a>
Upvotes: 1
Reputation: 554
I would look at using one of the Sluggable packages. https://packagist.org/?q=sluggable I have used the one by Spatie before and it works well.
Once you create your new entity/model and you then have a slug you will need to create a route to a controller which looks up the entity using the slug field.
$thing = Thing::whereSlug($request->get('slug'))->firstOrFail();
Upvotes: 0