15

I am trying to finish this middleware in larval that checks to make sure is subscribed to a subscription plan. If the user is not it redirects to the payment page.

public function handle($request, Closure $next)
{
    if(Auth::check()){
        if (Auth::user()->subscribed('main')) {
            return true;
        }else{
            return view('payments.payment')->with('user',Auth::user());
        }
    }else{
        abort(403, 'Unauthorized action.');
    }
    return $next($request);
}

I am getting this error with not much luck finding a solution Call to a member function setCookie() on null.

Amir
  • 179
  • 2
  • 14
John Freedom
  • 471
  • 4
  • 6
  • 11

4 Answers4

29

change

return view('payments.payment')

to

return response()->view('payments.payment')
buddemat
  • 4,552
  • 14
  • 29
  • 49
12

The problem is where you are returning true. A middleware should return a response-style object, not a boolean.

Since that is your "good" path and you want to proceed with your application logic, you should replace return true; with return $next($request);

public function handle($request, Closure $next)
{
    if(Auth::check()){
        if (Auth::user()->subscribed('main')) {
            return $next($request);
        }else{
            return view('payments.payment')->with('user',Auth::user());
        }
    }else{
        abort(403, 'Unauthorized action.');
    }
}

On an unrelated recommendation, you can clean up your conditional logic a bit to make your code easier to read/follow:

public function handle($request, Closure $next)
{
    // If the user is not logged in, respond with a 403 error.
    if ( ! Auth::check()) {
        abort(403, 'Unauthorized action.');
    }

    // If the user is not subscribed, show a different payments page.
    if ( ! Auth::user()->subscribed('main')) {
        return view('payments.payment')->with('user',Auth::user());
    }

    // The user is subscribed; continue with the request.
    return $next($request);
}
Aken Roberts
  • 13,012
  • 3
  • 34
  • 40
  • 7
    Note that trying to return a view from middleware will still cause the error. It is better to return a redirect response to the route that handles the view instead of trying to return the view itself: `return redirect()->route('route.to.payments.payment');` – newUserName02 Mar 20 '19 at 18:04
5

return response(view('payments.payment')->with('user',Auth::user()));

Nayan Zala
  • 61
  • 1
  • 1
3

i solve by redirect to other routereturn redirect()->to('route');

asghar
  • 437
  • 5
  • 5