我有一个像 /locations/name-of-the-location.ID
我的路线是:
Route::get('locations/{slug}.{location}', ['as' => 'locations.show', 'uses' => 'LocationsController@show'])->where([
'location' => '[0-9]+',
'slug' => '[a-z0-9-]+'
]);
现在我想检查提供的 slug 是否与我的模型保存在数据库列“slug”中的相同(因为 slug 可能已更改)。如果没有,那么我想重定向到正确的路径。
最好的地方在哪里?我想到了 \App\Providers\RouteServiceProvider- 但是当我尝试在Route::currentRouteName()
那里使用时,我得到 NULL,可能是因为在 RouteServiceProvider 的 boot() 方法中该方法“为时过早”。
我可以做的是使用 path(),但这对我来说似乎有点脏,因为我使用其他语言的路由前缀。
这是我尝试过的(我正在使用一个小助手类RouteSlug
) - 当然它不起作用:
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;
}
});
}
}
所以最后我想出了一个中间件:
App\Http\Middleware\CheckSlug
public function handle($request, Closure $next)
{
if ($redirect = RouteSlug::checkRedirect(Route::currentRouteName(), $request->location->id, $request->location->slug, $request->slug))
{
return redirect($redirect);
}
return $next($request);
}
我的路线是这样的:
Route::get('locations/{slug}.{location}', ['as' => 'locations.show', 'uses' => 'LocationsController@show'])->where([
'location' => '[0-9]+',
'slug' => '[a-z0-9-]+'
])->middleware(App\Http\Middleware\CheckSlug::class);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句