Laravel - Passing variables from Middleware to controller/route

前端 未结 2 1971
旧巷少年郎
旧巷少年郎 2021-02-19 19:02

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:



        
2条回答
  •  春和景丽
    2021-02-19 19:25

    I would leverage laravel's IOC container for this.

    in your AppServiceProvider's register method

    $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.

    In your TwilioWorkspaceCapability class:

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

提交回复
热议问题