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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32228176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:15:44  来源:igfitidea点击:

Laravel - Passing variables from Middleware to controller/route

laravellaravel-middleware

提问by ecorvo

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:

还有其他人使用 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.

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

采纳答案by mdamia

pass key value pair like this

像这样传递键值对

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

or to your action

或者你的行动

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

You can pass data the view using with

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

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

in your middleware

在你的中间件中

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

    return $next($request);
 }

in your controller

在你的控制器中

 return Request::get('token');

回答by stef

I would leverage laravel's IOC container for this.

我会为此利用 laravel 的 IOC 容器。

in your AppServiceProvider's register method

在您的 AppServiceProvider 的注册方法中

$this->app->singleton(TwilioWorkspaceCapability::class, function() { return new TwilioWorkspaceCapability; });

This will mean that wherever it you DI (dependancy inject) this class in your application, the same exact instance will be injected.

这意味着无论您在应用程序中 DI(依赖注入)这个类的任何地方,都将注入相同的实例。

In your TwilioWorkspaceCapability class:

在您的 TwilioWorkspaceCapability 类中:

class TwilioWorkspaceCapability {

    /**
     * The twillio token
     * @var string
     */
    protected $token;


    /**
     * Get the current twilio token
     * @return string
     */
    public function getToken() {
        return $this->token;
    }

    ... and finally, in your handle method, replace the $token = ... line with:
    $this->token = $workspaceCapability->generateToken();
}

Then, in your route:

然后,在您的路线中:

Route::get('/manage', ['middleware' => 'twilio.workspace.capability', function (Request $request, TwilioWorkspaceCapability $twilio) {
    return view('demo.manage', [
        'manage_link_class' => 'active',
        'token' => $twilio->getToken(),
    ]);
}]);