Thursday, March 9, 2017

Laravel: Check if slug in a route is equal to slug in database

I have an url like /locations/name-of-the-location.ID

My route is:

Route::get('locations/{slug}.{location}', ['as' => 'locations.show', 'uses' => 'LocationsController@show'])->where([
    'location' => '[0-9]+', 
    'slug' => '[a-z0-9-]+'
]);

Now I want to check if the slug provided is the same that is saved in the database column 'slug' with my model (because the slug may have changed). If not, then I want to redirect to the correct path.

Where is the best place to do that? I thought of \App\Providers\RouteServiceProvider- but when I try to use Route::currentRouteName() there, I get NULL, maybe because it is 'too early' for that method in the boot() method of RouteServiceProvider.

What I could do, is to work with the path(), but that seems a bit dirty to me, because I work with route prefixes in an other language.

Here's what I tried (I am using a little helper class RouteSlug) - of course it does not work:

public function boot()
{
    parent::boot();

    if (strstr(Route::currentRouteName(), '.', true) == 'locations')
    {
        Route::bind('location', function ($location) {
            $location = \App\Location::withTrashed()->find($location);
            $parameters = Route::getCurrentRoute()->parameters();
            $slug = $parameters['slug'];

            if ($redirect = \RouteSlug::checkRedirect(Route::getCurrentRoute()->getName(), $location->id, $location->slug, $slug))
            {
                return redirect($redirect);
            }
            else 
            {
                return $location;
            }

        });
    }
}



via sugo

Advertisement