Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.3: How to use Auth in Service Provider?

I am passing a value in shared view by taking value from table. I need to know user ID for the purpose but Auth::check() returns false. How do I do it? Below is code:

public function boot()
    {
        $basket_count = 0;
        if (Auth::check()) { //always false
            $loggedin_user_id = Auth::user()->id;
            $basket_count = Cart::getBasketCount();
        }
        view()->share('basket_count', $basket_count);
    }
like image 247
Volatil3 Avatar asked Sep 01 '25 06:09

Volatil3


1 Answers

OK turns out that ServiceProviders are not place for such things. The best thing is a Middleware. So if you want to call Auth, create middleware and pass value to views.

public function handle($request, Closure $next)
    {            
        $basket_count = 0;
        if ($this->auth) { //always false
            $loggedin_user_id = $this->auth->user()->id;
            $basket_count = Cart::getBasketCount($loggedin_user_id);
        }
        view()->share('basket_count', $basket_count);

        return $next($request);
    }
like image 163
Volatil3 Avatar answered Sep 03 '25 00:09

Volatil3