Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
831 views
in Technique[技术] by (71.8m points)

laravel - Call to a member function setCookie() on null

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...