How Can I Pass Variable related to Auth in multiple laravel controller?

157 views Asked by At

I have multiple method like below in my laravel controller :

public function daily(){
    $sites = Site::all()->where('owner_id', '==', Auth::user()->owner_id);
        return view('backend.daily',compact('sites'));
}
public function weekly(){
    $sites = Site::all()->where('owner_id', '==', Auth::user()->owner_id);
        return view('backend.weekly',compact('sites'));
}
public function yearly(){
    $sites = Site::all()->where('owner_id', '==', Auth::user()->owner_id);
        return view('backend.yearly',compact('sites'));
}
...

I used that in controller constructer :

public function __construct() {
        $sites = Site::all()->where('owner_id', '==', Auth::user()->owner_id);
        View::share('sites', $sites);
}

and use in AppserviceProvider in boot() method , but that doesn't work and get bellow error :

"Trying to get property 'owner_id' of non-object"

while in normal use it has no error!

in every method i've used one varible called $sites but it used in multiple views , i want to use $sites once and my code want to be like this shorter :

public function daily(){
        return view('backend.daily',compact('sites'));
}
public function weekly(){
        return view('backend.weekly',compact('sites'));
}
public function yearly(){
        return view('backend.yearly',compact('sites'));
}
...

How can i achieve this?

1

There are 1 answers

6
Zeshan On

Try this:

optional(Auth::user())->owner_id

If the user is not logged in, you'll probably not be able to get sites from the database.