Try   HackMD

報錯 Trying to get property of non-object

嘗試從非物件中索取某屬性

laravel報錯 版本7

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Trying to get property 'role' of non-object

程式碼如下

@if (Auth::user()->role == '1') <div class="card-footer text-muted"> <a href="/product/edit/{{$product->id}}" class="btn btn-warning"><i class="fas fa-edit"></i></a> <a href="/product/delete/{{$product->id}}" class="btn btn-danger"><i class="fas fa-trash-alt"></i></a> </div> @endif

先看前情提要 好用的Blade語法實例(點我)

這其實是一個未登入報錯,laravel好像常有這種錯誤(?),我也似懂非懂。
當使用@if又透過Auth索取值的時候,訪客就遭殃了,我也不知道為什麼@if要波及到他,不過@if判斷所有瀏覽這個頁面的人,包含未登入的訪客,都必須確認有沒有符合條件的值,符合的值可以看到被包起來的程式碼,不符合的,就看不到被包起來的程式碼。
但訪客根本就沒註冊,哪來什麼值啊。所以遭殃了。

怎麼解決?
查了好久決定修改他的描述,在@if外面多包一層,怎麼說呢
我先判斷瀏覽這個頁面的人是不是訪客,這樣好像讓這個頁面可以接受訪客的存在,或者說這個頁面忽然認知到有訪客這種生物,所以給了訪客一個位置,就不會波及到他了,我猜的。

第一種方法
@guest @else @endguest包起來

@guest @else @if (Auth::user()->role == '1') <div class="card-footer text-muted"> <a href="/product/edit/{{$product->id}}" class="btn btn-warning"><i class="fas fa-edit"></i></a> <a href="/product/delete/{{$product->id}}" class="btn btn-danger"><i class="fas fa-trash-alt"></i></a> </div> @endif @endguest

第二種方法
外面多一層@if (auth()->guest())包起來 原本的@if變成@elseif

@if (auth()->guest()) @elseif (Auth::user()->role == '1') <div class="card-footer text-muted"> <a href="/product/edit/{{$product->id}}" class="btn btn-warning"><i class="fas fa-edit"></i></a> <a href="/product/delete/{{$product->id}}" class="btn btn-danger"><i class="fas fa-trash-alt"></i></a> </div> @endif
tags: laravel laravel.7 blade 報錯