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

时间:2015-08-26 13:36:16

标签: laravel laravel-middleware

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

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

其他人也使用闪光灯进行吸烟:

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

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

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

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

2 个答案:

答案 0 :(得分:9)

像这样传递键值对

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

或您的行动

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

您可以使用

传递视图数据
 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');

答案 1 :(得分:1)

我会利用laravel的IOC容器。

在AppServiceProvider的注册方法

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

这意味着无论您在应用程序中使用DI(依赖注入)此类,都会注入相同的实例。

在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();
}

然后,在你的路线中:

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