Search code examples
phplaravelurllaravel-bladelaravel-route

Replacing object ID by object name on URL on Laravel route


I am trying to make my URL more SEO friendly on my Laravel application by replacing the ID number of a certain object by the name on the URL when going to that specific register show page. Anyone knows how?

This is what I got so far and it displays, as normal, the id as the last parameter of the URL:

web.php

Route::get('/job/show/{id}', ['as'=>'website.job.show','uses'=>'HomeController@show']);

Controller method

public function show($id){
        $job = Job::findOrFail($id);
        return view('website.job')->with(compact('job'));
    }

Blade page where there is the link to that page

<a href="{{route('website.job.show', $job->id)}}">{{$job->name}}</a>

Solution

  • You can overwrite the key name of your Job model:

    public function getRouteKeyName()
    {
        return 'name';
    }
    

    Then in your route simply use {job}:

    Route::get('/job/show/{job}', ...);
    

    And to call your route:

    route('website.job.show', $job);
    

    So your a tag would look like this:

    <a href="{{ route('website.jobs.show', $job) }}">{{ $job->name }}</a>
    

    Inside your controller, you can change the method's signature to receive the Job automatically:

    public function show(Job $job)
    {
        return view('website.job')
            ->with(compact('job'));
    }
    

    For more information, look at customizing the key name under implicit binding: https://laravel.com/docs/5.8/routing#implicit-binding