2016-07-30 89 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' }}