首页 > 解决方案 > Trying to get property 'name' of non-object laravel 8

问题描述

Trying to get property 'name' of non-object (View: D:\Courses\Buildwithangga\BWAFD\nomads-app\resources\views\includes\admin\navbar.blade.php)

I'm using Laravel 8, but i did not install jetstream, i install laravel/ui (Is that make any problem??)

And when i add {{ Auth::user()->name }} in navbar.blade.php, it will run error

This is my navbar.blade.php

<!-- Sidebar Toggle (Topbar) -->
<button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3">
  <i class="fa fa-bars"></i>
</button>

<!-- Topbar Navbar -->
<ul class="navbar-nav ml-auto">
  <li class="nav-item dropdown no-arrow">
    <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
      <span class="mr-2 d-none d-lg-inline text-gray-600 small">
        {{ Auth::user()->name }}
      </span>
      <img class="img-profile rounded-circle" src="https://source.unsplash.com/QAB-WJcbgJk/60x60">
    </a>
    <!-- Dropdown - User Information -->
    <div class="dropdown-menu dropdown-menu-right shadow animated--grow-in" aria-labelledby="userDropdown">
      <a class="dropdown-item" href="#" data-toggle="modal" data-target="#logoutModal">
        <i class="fas fa-sign-out-alt fa-sm fa-fw mr-2 text-gray-400"></i>
        Logout
      </a>
    </div>
  </li>

</ul>

Thankyou :)

标签: laravel

解决方案


That's because when a user is not logged in, Auth::user() will be null and you cannot access a property name on null.

You can tackle this in

@auth
<span class="mr-2 d-none d-lg-inline text-gray-600 small">
    {{ Auth::user()->name }}
</span>
@endauth

//OR

<span class="mr-2 d-none d-lg-inline text-gray-600 small">
    {{ optional(Auth::user())->name }}
</span>

Out of the above two options using @auth is better because in the second option an empty span will still be included in the page. Where as with @auth whatever is in between @auth and @endauth will only be included on the page if user is logged in.


推荐阅读