首页 > 解决方案 > 向所有路由添加变量

问题描述

我需要向我的应用程序中的所有路由显示一个变量(取自用户模型),这对显示它的路由没有影响。因此 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)。

标签: laravelurl

解决方案


到目前为止我的知识:如果你想使用不同的路径,你需要写下路由中的每条路径。但是选择哪一个的决定将由中间件完成。因此,您创建自己的中间件并在此处附加到所有带有->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);
}
}

希望你能明白。在此处检查路径。不要忘记在其中注册您的中间件Kernel.php,这是我不久前使用的教程。


推荐阅读