803 0 0 0
Last Updated : 2025-04-28 21:56:28
In this snippet I will teach you how to modify model binding slug in URL
Hello guys,
In this snippet I will teach you how to modify model binding slug in URl, let see an example of this (you have a blog and have articles and when open an article you want its URL to contain blog title but without any spacing just convert spacing into dashes for SEO for example ), Let's get started
1- Route
first of all we have to create a route for opening the artricle like this
Route::get('/article/{blog:title}', [FrontController::class, 'article'])->name('article');
// Please note slug title in the route ... meaning that we will call the article by blog title not ID
2- In blade view
Second step is we need to convert slug title and ensure that we converting spacing iton dashes in the blog title so we can use helper str::slug() method like this
<?php
use Illuminate\Support\Str;
$slug = Str::slug($blog->title, '-');
?>
// this will convert the blog title from containing spacing to dashes
// like the example below
// FROM (15 react app ideas for developers) TO (15-react-app-ideas-for-developers)
after this you have to call the route and pass the new slug to the route as a parameter like this
<a href="{{ route('front.article', ['blog' => $slug]) }}" class="blog-card">
// blog title here
</a>
// Please note that we change $blog title to new $slug
3- RouteServiceProvider
Third step of this technique is to define what article will be returned when calling that new slug title because that title with dashes not included in any article title so go to RouteServiceProvide.php and jump into boot method and define whit article to be returned corresponding to the new slug title like this
use Illuminate\Support\Facades\Route;
Route::bind('blog', function ($value) {
return Blog::where('title', 'like', '%'.str_replace("-"," ",$value).'%')->firstOrFail();
});
// this will convert dashes in new slug to spaces again and will search for blog title that containing that title
// Please note the '%' sign -> I used this to search for blog title in the first or end of blog title as when for
// example the title contains ? mark .. this will ignore any marks in url title