Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

php - 在laravel中的AppServiceProvider中使用身份验证(use authentication in a AppServiceProvider in laravel)

I am using Laravel so every logged in user can has a cart so I want to access their cart in my master blade because it's on the header and show all cart products in every pages

(我正在使用Laravel,因此每个登录的用户都可以拥有一个购物车,因此我想在主刀片中访问他们的购物车,因为它位于标题上,并在每个页面中显示所有购物车产品)

so I use this in AppServiceProvider but I need to check if the user logged in it will show cart

(所以我在AppServiceProvider中使用它,但是我需要检查登录的用户是否会显示购物车)

    public function boot()
    {

        view()->composer('app.shop.2.layouts.master', function($view) {

          $data = Auth::user()->cart()->get()->first()->products();
          $view->with('data', $data);
        });
    }

so everything is ok until the user is logged in but when the user is not logged in it gives me this error :

(所以一切正常,直到用户登录,但是当用户未登录时,出现此错误:)

Call to a member function cart() on null (View: F:\larav-pay\payment\resources\views\app\shop\2\index.blade.php)

(在null上调用成员函数cart()(视图:F:\ larav-pay \ payment \ resources \ views \ app \ shop \ 2 \ index.blade.php))

  ask by hassan khosro translate from so

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

1 Answer

0 votes
by (71.8m points)

You can use Auth::check() to check whether the user is authenticated or not like this:

(您可以使用Auth::check()来检查用户是否已通过身份验证,如下所示:)

public function boot()
{
    view()->composer('app.shop.2.layouts.master', function($view) {
        if (Auth::check()){
            $data = Auth::user()->cart()->get()->first()->products();
            $view->with('data', $data);
        }
    });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...