124697
124697

Reputation: 21901

Trying to get property of non-object error but works when page is refreshed

I get the error in the title sometimes but when I refresh a few times, my application works again.

Laravel.log shows this:

[2016-12-19 13:17:22] local.ERROR: exception 'ErrorException' with message 'Trying to get property of non-object' in

storage\framework\views\e81b4a67320194ba9a4782ec91b02d51:12

storage/framework/views/e81b4a67320194ba9a4782ec91b02d51.php line 12:

<span class="block m-t-xs">
    <strong class="font-bold"><?php echo e(Auth::user()->name); ?></strong> <!--line 12-->
</span>

Upvotes: 0

Views: 353

Answers (4)

Saumya Rastogi
Saumya Rastogi

Reputation: 13709

You should check if the session has the authenticated user or not using auth()->check():

<span class="block m-t-xs">
    <strong class="font-bold">
        <?php echo (auth()->check()) ? e(Auth::user()->name) : ''; ?>
    </strong>
</span>

You can use ternary operator to check if the user is authenticated or not.

Hope this helps!

Upvotes: 0

124697
124697

Reputation: 21901

For some reason Auth::check() returned false but app didn't log me out. After clearing cookies and logging in again this error stopped happening.

I suspect the issue was that I changed the user and auth quite a bit but didn't clear cookies

Upvotes: 0

aimme
aimme

Reputation: 6818

do Auth::check() or Auth::user() before trying to access fields in user object. Its because that you are trying to get a property of the user object, but the user object is null. like this

<span class="block m-t-xs">
    @if(Auth::check())
    <strong class="font-bold">
        {{ Auth::user()->name }}
    </strong>
    @endif
</span>

Upvotes: 4

Md. Abutaleb
Md. Abutaleb

Reputation: 1645

Why you 're trying to use e()? try to dd(Auth::user()) then see the result or try

{{ Auth::user()->name }} 

Upvotes: -1

Related Questions