DisplayName
DisplayName

Reputation: 129

Laravel 5.5 Trying to get property of non-object

public function __construct()
{
    view()->share('tags', DB::table('tags')->where('view', Auth::user()->view)->get());
    $this->middleware('auth');
}

I receive:

(1/1) ErrorException Trying to get property of non-object

Why? When I try to return Auth::user()->view; I got 2. But when I manually type ->where('view', 2) then everything is ok. How can I fix this? Thanks in advance.

Upvotes: 1

Views: 3675

Answers (2)

Onix
Onix

Reputation: 2179

Try to return gettype (Auth::user()->views) to see if views its an integer. if not just (int)Auth::user()->views to make it.

or try to assign it to a variable like this:

$views = (int)(Auth::user()->views);

then use it ...->where('view', $views)->get());

Upvotes: 1

Honarkhah
Honarkhah

Reputation: 553

you used auth middleware after Auth::user()->view , it's wrong

public function __construct()
{
    $this->middleware('auth'); // firstly auth check , after that can use Auth::user() , before them Auth::user() return null   and you cant use ->view on null , when ErrorException Trying to get property of non-object
    view()->share('tags', DB::table('tags')->where('view', Auth::user()->view)->get());
}

your user is not signed please check

Auth::check()

and after that use

Auth::user()->view

Upvotes: 1

Related Questions