How to create URL slugs in Laravel without ‘slug’ field in database

Generally all websites around the internet using slugs in their urls, This gives search engines a simple way to access to your website and archive them, this will produce a great SEO too.

Creating URLs will be easy when you take that in consideration when you are starting designing your database schema, so you set “slug” field in the concerned table from the beginning.

In php we can easy use built in function on strings to create slug from string, something like this:

$slug = trim('site title', '-');

But as I did, I’m not set a slug field in the database schema, so when I wanted to use them on my Laravel project I stuck.. so I was thinking in a speedy and simple way to do that without refreshing my database.

You know Developers are lazy.. think to do it easily 😀

I have an product table with this fields: id | name | code | description …

So I decided to use field “name” as a slug to my products URL

My old Route:

Route::get('/product/product-details/{id}', [ProductsController::class, 'see_more_about_project'])->name('product.single');

My Updated Route

Route::get('/product/product-details/{id}-{slug}', [ProductsController::class, 'see_more_about_project'])->name('product.single');

In my product Model App\Models; I create this method that return an array with product id and name as a slug

    // creating slug 
    public function get_slug_params_for_urls()
        $slg = Str::slug($this->name, '-');
        return [
            $this->id, // product id
            $slg, // slug

Str::slug is a Laravel Helpers

Don’t forget to import “use Illuminate\Support\Str;” when you are using Str::slug

So now in your route link to the product details we will use our above function to call url parameters that include name and id

Something like this link

<a href="{{ route('product.single', $product->get_slug_params_for_urls()) }}"><h4>{{ $product->name }}</h4></a>

Let’s suppose that our product name is “Sport Watch” with the id=5, based on my Route, the output url will be:

Until here we have set the URLs without change the database, Hope this post can helps someone.

Leave a Reply

Your email address will not be published. Required fields are marked *