John R.
John R.

Reputation: 43

Laravel middleware for subscription

I am trying to write middleware in Laravel 5 that will check if a user has a subscription, and it isn't canceled. If it doesn't exist or is canceled, then they will be locked into one page (billing). Problem is, I end up in a redirect loop. I understand why, but I just can't figure out what the correct thing to do is. Thanks in advance

public function handle($request, Closure $next)
{


    if (\Auth::check()) 
    {
        // if subscription does not exist
        if (\Auth::user()->hospital->subscription == null || \Auth::user()->hospital->subscription !== 'Active') {
           return redirect('billing');
        }

    }
    return $next($request);
}

Upvotes: 3

Views: 2393

Answers (1)

manix
manix

Reputation: 14747

Problem is, I end up in a redirect loop.

Looks like you are applying the middleware in the whole application including the billing page. So, you need to specify where the middleware class should be considered, this can be achieved at /app/Http/kernel.php.

Also, you can considere make an additional validation at your middleware clas like:

// billing (http://example.com/billing)
$path = $request->path();

if ($path !== 'billing')
{

    if (\Auth::check()) 
    {
        // if subscription does not exist
        if (\Auth::user()->hospital->subscription == null || \Auth::user()->hospital->subscription !== 'Active') {
           return redirect('billing');
        }

    }
}
return $next($request);

Upvotes: 1

Related Questions