# 報錯 Trying to get property of non-object #### 嘗試從非物件中索取某屬性 ##### laravel報錯 版本7 ![](https://i.imgur.com/pVVAFoE.png) ###### Trying to get property 'role' of non-object 程式碼如下 ```php= @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語法實例(點我)](https://hackmd.io/@codehome/B12uimypK) :::danger 這其實是一個未登入報錯,laravel好像常有這種錯誤(?),我也似懂非懂。 當使用@if又透過Auth索取值的時候,訪客就遭殃了,我也不知道為什麼@if要波及到他,不過@if判斷所有瀏覽這個頁面的人,包含未登入的訪客,都必須確認有沒有符合條件的值,符合的值可以看到被包起來的程式碼,不符合的,就看不到被包起來的程式碼。 但訪客根本就沒註冊,哪來什麼值啊。所以遭殃了。 ::: :::info 怎麼解決? 查了好久決定修改他的描述,在@if外面多包一層,怎麼說呢... 我先判斷瀏覽這個頁面的人是不是訪客,這樣好像讓這個頁面可以接受訪客的存在,或者說這個頁面忽然認知到有訪客這種生物,所以給了訪客一個位置,就不會波及到他了,我猜的。 ::: :::success 第一種方法 用`@guest` `@else` `@endguest`包起來 ::: ```php= @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 ``` :::success 第二種方法 外面多一層`@if (auth()->guest())`包起來 原本的`@if`變成`@elseif` ::: ```php= @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` `報錯`