Answer the question
In order to leave comments, you need to log in
How to get current user id in service provider?
There is a basket that is displayed on all pages and next to it is a counter (shows how many items are in the basket).
Actually, through View:: share I'm trying to transfer the number of goods to all views.
I made a service provider, in the boot() method I registered View::share( 'count', Cart::where('id', Auth::id)->sum('count') ) and included it in config/app in at the very end.
As a result, everything works, except that Auth::id() returns null. (when replacing "Auth::id()" with "1", everything works fine).
Or is there a better way to organize it?
Laravel 5.4
Answer the question
In order to leave comments, you need to log in
The first link in Google, well, why are you so :)
Can be done through Middleware
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
class SetViewVariables
{
protected $auth;
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
public function handle($request, Closure $next)
{
$user = $this->auth->user();
view()->share('user', $user);
return $next($request);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question