Laravel - 将变量从中间件传递到控制器/路由

eco*_*rvo 12 laravel laravel-middleware

如何将变量从中间件传递到控制器或执行此类中间件的路由?我看到一些关于将它附加到请求的帖子,如下所示:

$request->attributes->add(['key' => $value);
Run Code Online (Sandbox Code Playgroud)

还有其他人用闪光灯吸食:

Session::flash('key', $value);
Run Code Online (Sandbox Code Playgroud)

但我不确定这是最佳做法,还是有更好的方法来做到这一点?这是我的中间件和路线:

namespace App\Http\Middleware;

use Closure;

class TwilioWorkspaceCapability
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $workspaceCapability = new \Services_Twilio_TaskRouter_Workspace_Capability("xxxxx", "xxxx", "xxxx");
        $workspaceCapability->allowFetchSubresources();
        $workspaceCapability->allowDeleteSubresources();
        $workspaceCapability->allowUpdatesSubresources();
        $token = $workspaceCapability->generateToken();
        //how do I pass variable $token back to the route that called this middleware
        return $next($request);
    }
}

Route::get('/manage', ['middleware' => 'twilio.workspace.capability', function (Request $request) {
    return view('demo.manage', [
        'manage_link_class' => 'active',
        'twilio_workspace_capability' => //how do I get the token here?...
    ]);
}]);
Run Code Online (Sandbox Code Playgroud)

仅供参考我之所以决定使用中间件是因为我计划在其生命周期中缓存令牌,否则这将是一个可怕的实现,因为我会在每个请求上请求一个新令牌.

mda*_*mia 9

像这样传递键值对

$route = route('routename',['id' => 1]);
Run Code Online (Sandbox Code Playgroud)

或者你的行动

$url = action('UserController@profile', ['id' => 1]);
Run Code Online (Sandbox Code Playgroud)

您可以使用with传递视图数据

 return view('demo.manage', [
    'manage_link_class' => 'active',
    'twilio_workspace_capability' => //how do I get the token here?...
]) -> with('token',$token);
Run Code Online (Sandbox Code Playgroud)

在你的中间件中

 public function handle($request, Closure $next)
 {
    $workspaceCapability = new .....
    ...
    $request -> attributes('token' => $token);

    return $next($request);
 }
Run Code Online (Sandbox Code Playgroud)

在你的控制器中

 return Request::get('token');
Run Code Online (Sandbox Code Playgroud)

  • 注意Laravel 5这是如何在请求中添加参数:`$ request-> attributes-> add(['myAttribute'=>'myValue']);` (6认同)