[英]Laravel - Best way to correct the url on every request?
what is the best way to correct the url in specific models?在特定型号中纠正 url 的最佳方法是什么? I have few models with a slug and the url schema is:我有几个带有蛞蝓的模型,url 架构是:
Route::get('/abc/{id}/{slug?}', 'AbcController@show')->name('abc.show');
Route::get('/abc/{id}/{slug?}/def-show', 'AbcDefController@show')->name('abc.def.show');
Route::get('/abc/{id}/{slug?}/def', 'AbcDefController@create')->name('abc.def.create');
On every controller I'm asking it like this:在每个 controller 上,我都这样问:
if ($slug !== $abc->slug) {
return redirect()->to(route([controller-function-specific], [$abc->id, $abc->slug]));
}
return view('[blade-template]', compact(['abc']))->withCanonical($abc->slug);
What is the better approach?更好的方法是什么? I tried it with observers ("retrieved") but I don't need that for every function/action in the controller (eg "index" which only lists all elements and doesnt need slug) and also the route is different.我与观察者一起尝试过(“检索”),但我不需要 controller 中的每个功能/动作(例如“索引”,它只列出所有元素并且不需要 slug)而且路线也不同。
My solution works but it's redundant because I insert this specific part in a lot functions/actions.我的解决方案有效,但它是多余的,因为我将这个特定部分插入到很多功能/操作中。 I could write it into the model but this doesn't solve the redundant calling like checkSlug('[ROUTE]').我可以将它写入 model 但这并不能解决像 checkSlug('[ROUTE]') 这样的冗余调用。
Any ideas?有任何想法吗?
Use Explicit Route Model Binding in your RouteServiceProvider
's boot
function在RouteServiceProvider
的boot
function 中使用显式路由 Model 绑定
public function boot()
{
parent::boot();
Route::bind('abc', function($value) {
return \App\Abc::where('id', $value)
->where('slug', $value)->first() ??
redirect(); // Custom resolution logic here
});
}
Note that this makes the slug
required just like your if ($slug !== $abc->slug)
check请注意,这使得slug
就像您的if ($slug !== $abc->slug)
检查一样
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.