【发布时间】:2019-10-14 00:18:25
【问题描述】:
我需要向我的应用程序中的所有路由显示一个变量(取自用户模型),这对显示它的路由没有影响。因此 home/variable 将向所有用户显示相同的主页,而不管该变量如何。如果用户只是访问 myapp/home,则该变量会将自身附加到 url 作为 myapp/home/variable。
我已经在 web.php 中得到了我想要的结果,但是我必须对每条路由都这样做,所以如果我的应用程序有两个页面,我会对 /home 和 /example 执行相同的重定向。这也意味着每当我从另一个控制器重定向时,我都必须添加变量。
Route::get( '/example',function(){
$var = Auth::user()->thevariable;
return redirect('example/'.$var);
});
Route::get( 'example/{var}','ExampleController@index');
// changes the url from example, to example/variable, and also returns
the correct controller / view if directed to example/variable.
在我的控制器中,如果需要,我会做这样的事情来重定向:
return redirect()->action('HomeController@index',$user->thevariable)
//I can also just redirect to the /home url and the variable is added
automatically, but this messes up passing session data.
使用作曲家、中间件甚至通过 RouteServiceProvider 可以做得更好吗?如果有人能指出我正确的方向,将不胜感激(laravel 5.4)。
【问题讨论】:
-
所以有例如网站
/settings和/settings/{id}?用例是什么? -
所以页面
/settings与/settings/{id}相同,如果用户在其 url 中输入 /settings{thevariable}将自动附加,因此无论他们访问哪个页面或如何获取那里的 url 总是这样写的:/any/path/{constantvariable}