Search code examples
laravelmiddlewarelaravel-5.3laravel-cashier

Is it possible and how do I if so to pass a variable parameter to a Middleware in Laravel


I looking to set up a Middleware to check if the user is a subscriber to the page that they are on. I have tried a couple of options but both has required passing the URL to the Middleware.

The Route

Route::get('premium/{id}', function ($id) {
    return $id;
})->middleware('subscribe:{$id}');

The Middleware

 public function handle($request, Closure $next, $subscribe)
    {
        //dd($subscribe);
        $c = DB::table('suscribes')->where('user_id', $request->user()->id)->where('subscribed_to', $subscribe)->count();

        return $next($request);
    }

The above $subscribe obviously returns a string of {$id} but have tried concatenating. Is there a better way?

As I am using Cashier and Stripe I have also tried setting up a new plan for each user. From docs.

public function handle($request, Closure $next)
{
    if ($request->user() && ! $request->user()->subscribed('main')) {
        // This user is not a paying customer...
        return redirect('billing');
    }

    return $next($request);
}

But I still need to pass the variable to 'main'.


Solution

  • I'm not sure if I understand your requirement completely. But to get the value of some Requests route Parameter you can use $request->route('param-identifyer') function. Passing {$id} as parameter to the middleware is the wrong approach.

     public function handle($request, Closure $next, $subscribe)
        {
            dd($request->route('id'));
    
            $c = DB::table('suscribes')->where('user_id', $request->user()->id)->where('subscribed_to', $subscribe)->count();
    
            return $next($request);
        }