laravel - 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 :)
解决方案
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.
推荐阅读
- php - PHPMailer 不工作:有新的方法吗?
- python - Pandas 数据框分组求和,同时忽略非数值
- tensorflow - 修复 seq2seq 模型的错误输出
- arrays - 如何使用 eloquent 在数组数组中搜索字符串
- angular - (Angular 2+)尝试设置基于 sessionStorage 的 var ngOnInit() 但在页面加载后未定义
- docker - 如何在 docker 容器中导出 DGraph 数据库(Windows)
- java - 错误:找不到属性“com.example.b3rk4.myapplication:layout_constraintTop_toTopOf”
- php - JSON API 到 HTML Koinex API
- javascript - 如何在多个鼠标悬停上更改光标
- d3.js - Music21 和 D3.js 用于音乐特征提取和可视化?