Laravel - Passing variables from Middleware to controller/route

左心房为你撑大大i 提交于 2019-12-04 01:05:42

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

 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');

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(),
    ]);
}]);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!