Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing across view in Laravel 5.4

I have a project where users are assgned to a client and I wannt to share that info across views.

In AppServiceProvider I added

use View;
use Auth;

and then amended boot to

if ( Auth::check() )
            {
                $cid = Auth::user()->client_id;
                $company = \App\Clients::first($cid);
                view::share('company',$company);
            }

but if I dd($company) I get

Undefined variable: company 
like image 522
Jim Avatar asked Dec 23 '22 17:12

Jim


2 Answers

This is because of the Auth is not working in AppServiceProvider

So your If condition return false

if you share data with all the views then your code like this without check Auth. then It will work.

$company = 'Some value';
view::share('company',$company);

dd($company);     // for print output.

Solution - For Alternate option you have to make Helper class.

like image 196
Chintan Kotadiya Avatar answered Dec 28 '22 06:12

Chintan Kotadiya


At the time the providers boot is run, the Auth guard has not been booted, so Auth::check() returns false, and Auth::user() returns null.

You could do the View::share in a middleware, or perhaps in the constructor of a controller (the base controller to share it across the whole application, or some particular controller if you need it in some subset of routes).

like image 44
alepeino Avatar answered Dec 28 '22 06:12

alepeino