Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - Passing variables from Middleware to controller/route

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.

like image 811
ecorvo Avatar asked Aug 26 '15 13:08

ecorvo


People also ask

How do you pass variables with middleware?

The most common pattern for passing variables on to other middleware and endpoint functions is attaching values to the request object req . In your case, that would mean having middlewares such as these: app. use(function (req, res, next) { req.

Can we apply middleware on controller in Laravel?

Laravel incorporates a middleware that confirms whether or not the client of the application is verified. If the client is confirmed, it diverts to the home page otherwise, it diverts to the login page. All controllers in Laravel are created in the Controllers folder, located in App/Http/Controllers.

How to get Param from route in Laravel?

We can access route parameters in two ways. One way is by using $request->route('parameter_name') ., where parameter_name refers to what we called the parameter in the route. In the handle method within the DumpMiddleware class created in the app/Http/Middleware/DumpMiddleware. php file.


1 Answers

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(),
    ]);
}]);
like image 146
stef Avatar answered Sep 21 '22 19:09

stef