2016-07-30 86 views
1

我有Post模型,其中有用戶函數返回用戶模型 - 帖子的創建者。Laravel:在刀片視圖中打印URL或默認值

class Post extends Model 
{ 
    /** 
    * Get the user that owns the post. 
    */ 
    public function user() 
    { 
     return $this->belongsTo(User::class); 
    } 
} 

在刀片鑑於我如何實現打印作者姓名

{{ $post->user->name or 'Anonymous' }} 

上面的代碼工作,但它是非常敏感嗯? 例如,我想這個代碼更改爲:

{{ $post->user->name, 'Anonymous' }} 

<?php $post->user->name or 'Anonymous' ?> 

結果? 試圖根據此代碼獲取非對象錯誤的屬性。我可能會跳過一些簡單但重要的事情。如何在刀片視圖中打印URL或默認值。僞代碼我的意思是:

{{ '<a href="url('/profile/' .$post->user->name)"></a>' or 'Anonymous' }} 

回答

2

嘗試

{{ isset($post->user->name) ? '<a href="url('/profile/' . $post->user->name)"></a>' : 'Anonymous' }} 

如果這不起作用(我沒有檢查它)嘗試這樣:

@if (isset($post->user->name)) 
    <a href="url('/profile/' . $post->user->name)"></a> 
@else 
    Anonymous 
@endif 
+0

當條件爲真時,第一個代碼將拋出「使用未定義的常量配置文件 - 假定'配置文件'」錯誤,並且當條件爲假時拋出匿名。第二個代碼在條件爲真時拋出簡單變量名稱,在條件爲假時拋出匿名。 '{{ $post->user->name }}'修復它 –

1

其實這個錯誤並不是因爲代碼是敏感的,這是因爲你實際上試圖訪問非對象值。

要實現你在找什麼:

{{ isset($post->user)?'<a href="url('/profile/' .$post->user->name)"></a>' : 'Anonymous' }}