0

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?

Amin Arjmand
  • 435
  • 7
  • 21

1 Answers1

0

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.

Zeshan
  • 2,496
  • 3
  • 21
  • 26
  • sir i don't have problem on authorization , i should use this where ```where('owner_id', '==', Auth::user()->owner_id``` it can not be ignored – Amin Arjmand Aug 01 '19 at 06:14
  • So this should work then: `where('owner_id', '==', optional(Auth::user())->owner_id)`. Did you try it? – Zeshan Aug 01 '19 at 06:16
  • yes this worked but it shows no record ! it look likes that sites variable is not defined when i dd($sites) on blade – Amin Arjmand Aug 01 '19 at 06:24
  • make sure you used `->get()` in the end to `where()`. Like `Site::where('owner_id', '==', Auth::user()->owner_id)->get();`. Try `dd($sites)` in the `AppServiceProvider` to make sure it contains data. – Zeshan Aug 01 '19 at 06:28
  • I've used this code in boot() method in AppServiceProveder and Constructor but it shows nothing and when i use dd($sites) it shows me empty collection ```Collection {#147 ▼ #items: [] }``` while i have data in normal mode! – Amin Arjmand Aug 01 '19 at 06:52
  • when i use $site variable in for example in yearly() mehod without ```->get()``` that shows me data in Collection – Amin Arjmand Aug 01 '19 at 06:57