laravel - 向所有路由添加变量
问题描述
我需要向我的应用程序中的所有路由显示一个变量(取自用户模型),这对显示它的路由没有影响。因此 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)。
解决方案
到目前为止我的知识:如果你想使用不同的路径,你需要写下路由中的每条路径。但是选择哪一个的决定将由中间件完成。因此,您创建自己的中间件并在此处附加到所有带有->middleware('myOwnMW');
. 它应该像:
<?php
namespace App\Http\Middleware;
use Closure;
class myOwnMW
{
public function handle($request, Closure $next)
{
if (Auth::user()->thevariable) {
//redirect to your path
$uri = $request->path() . '/'. $variableIwantToAttach;
return redirect($uri);
}
return $next($request);
}
}
推荐阅读
- azure-ad-b2c - 无法在 Azure AD B2C 自定义策略中查询自定义 REST API
- c# - C1 True DBGrid 2 复选框选中/取消选中 + 键
- python - 选择数据框中的行,而不是在具有不同形状数组的不同数据框中,并且对象不可迭代
- c# - 将 linq2db 与 .net 核心一起使用时出现“无法加载文件或程序集‘System.EnterpriseServices’”
- javascript - setSelectionRange 适用于输入字段,但如何将光标放在 contenteditable 字段的末尾?
- javascript - 寻找做这个动画的 DRY 方法
- java - Block unknown json properties on certain classes
- xcode10 - 如何在 Xcode 10 beta 中安装 iOS 12 模拟器?
- java - 分隔数字
- javascript - 在渲染之前确实需要一些帮助来弄清楚 componentWillMount() 的逻辑