Update model binding slug in URL

586 0 0 0

Last Updated : 2024-02-22 15:19:32

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

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

// 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

Mahmoud Anwar

Mahmoud Anwar

Back End Developer with a passion for developing innovative web applications that expedite the efficiency and effectiveness of organizational success. Well-versed in technology and writing code to create systems that are reliable and user-friendly. Also has the proven ability to motivate, educate, and collaborate effectively to build web applications and effectively track changes. Confident communicator, strategic thinker, and innovative creator to develop software that is customized to meet a company’s organizational needs, highlight their core competencies, and further their success.