Laravel-将变量从中间件传递到控制器/路由 [英] Laravel - Passing variables from Middleware to controller/route

查看:52
本文介绍了Laravel-将变量从中间件传递到控制器/路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将变量从中间件传递到执行该中间件的控制器或路由?我看到了一些有关将其附加到请求的信息,如下所示:

How can I pass variables from a middleware to a controller or a route that executes such middleware? I saw some post about appending it to the request like this:

$request->attributes->add(['key' => $value);

其他人也被闪光灯指住了

also others sugested using flash:

Session::flash('key', $value);

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

but I am not sure if that is best practice, or if there is a better way to do this? Here is my Middleware and route:

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?...
    ]);
}]);

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

FYI the reason I decided to use a middleware for this is because I plan to cache the token for its lifecycle otherwise this would be a horrible implementation, since I would request a new token on every request.

推荐答案

传递像这样的键值对

$route = route('routename',['id' => 1]);

或采取行动

$url = action('UserController@profile', ['id' => 1]);

您可以使用来通过视图传递数据

You can pass data the view using with

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

在您的中间件中

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

    return $next($request);
 }

在您的控制器中

 return Request::get('token');

这篇关于Laravel-将变量从中间件传递到控制器/路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆