我使用Hashid来隐藏Laravel 5中资源的id。
以下是路由文件中的路由绑定:
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);
});
在模型中:
public function getRouteKey()
{
$hashids = new 'Hashids'Hashids(env('APP_KEY'),8);
return $hashids->encode($this->getKey());
}
现在,这一切都很好——资源显示得很完美,ID也被散列了。但当我转到我的创建路由时,它是404——如果我删除App::abort(404),创建路由将转到资源"显示"视图,而没有任何数据。。。
这是创建路线:
Route::get('schedules/create', [
'uses' => 'SchedulesController@create',
'as' => 'schedules.create'
]);
展会路线:
Route::get('schedules/{schedule}', [
'uses' => 'Schedules Controller@show',
'as' => 'schedules.show'
]);
我还将模型绑定到路线:
Route::model('schedule', 'App'Schedule');
有什么想法为什么我的创建视图没有正确显示吗?索引视图显示良好。
为了解决这个问题,我不得不重新安排我的crud路线。
在Show路线之前创建所需的。。。
有一个包可以做您想要做的事情:https://github.com/balping/laravel-hashslug
还要注意,使用APP_KEY
作为盐不是一个好主意,因为它可能会暴露。
使用上面的包,你所需要做的就是在控制器中添加一个特性和类型提示:
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'));
}