在null上调用成员函数setCookie()

Joh*_*dom 5 laravel stripe-payments

我试图在幼虫中完成此中间件,以检查确保已订阅了订阅计划。如果用户不是,它将重定向到付款页面。

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);
}
Run Code Online (Sandbox Code Playgroud)

我遇到这个错误,运气不佳,没有找到解决方案。对null的成员函数setCookie()的调用。

小智 11

改变

return view('payments.payment')
Run Code Online (Sandbox Code Playgroud)

return response()->view('payments.payment')
Run Code Online (Sandbox Code Playgroud)

  • 如果返回“视图”,这是正确的答案。 (2认同)

Ake*_*rts 6

问题是你要回去的地方true。中间件应返回一个响应样式的对象,而不是布尔值。

由于这是您的“好”路径,并且您要继续执行应用程序逻辑,因此应替换return true;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.');
    }
}
Run Code Online (Sandbox Code Playgroud)

根据不相关的建议,您可以稍微整理一下条件逻辑,以使您的代码更易于阅读/关注:

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);
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,尝试从中间件返回视图仍会导致错误。最好将重定向响应返回到处理视图的路由,而不要尝试返回视图本身:`return redirect()-> route('route.to.payments.payment');` (2认同)

小智 5

返回响应(视图('付款.付款')-> with('用户',Auth :: user()));