Laravel 5 Route binding and Hashid

2.3k Views Asked by At

I am using Hashid to hide the id of a resource in Laravel 5.

Here is the route bind in the routes file:

Route::bind('schedule', function($value, $route)
{
    $hashids = new Hashids\Hashids(env('APP_KEY'),8);
    if( isset($hashids->decode($value)[0]) )
    {
        $id = $hashids->decode($value)[0];
        return App\Schedule::findOrFail($id);
    }
    App::abort(404);
});

And in the model:

public function getRouteKey()
{
    $hashids = new \Hashids\Hashids(env('APP_KEY'),8);
    return $hashids->encode($this->getKey());
}

Now this works fine the resource displays perfectly and the ID is hashed. BUT when I go to my create route, it 404's - if I remove App::abort(404) the create route goes to the resource 'show' view without any data...

Here is the Create route:

Route::get('schedules/create', [
  'uses' => 'SchedulesController@create',
  'as' => 'schedules.create'
]);

The Show route:

Route::get('schedules/{schedule}', [
  'uses' => 'Schedules Controller@show',
  'as' => 'schedules.show'
]);

I am also binding the model to the route:

Route::model('schedule', 'App\Schedule');

Any ideas why my create view is not showing correctly? The index view displays fine.

2

There are 2 best solutions below

0
On

Turns out to solve this, I had to rearrange my crud routes.

Create needed to come before the Show route...

0
On

There's a package that does exactly what you want to do: https://github.com/balping/laravel-hashslug

Also note, that it's not a good idea to use APP_KEY as salt because it can be exposed.

Using the above package all you need to do is add a trait and typehint in controller:

class Post extends Model {
    use HasHashSlug;
}
// routes/web.php
Route::resource('/posts', 'PostController');
// app/Http/Controllers/PostController.php

public function show(Post $post){
  return view('post.show', compact('post'));
}