Adam Mańkowski Adam Mańkowski - 4 months ago 14
PHP Question

Laravel: print URL or default value in blade view

I have Post model which has user function returning User model - creator of the post.

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


In blade view I achieved how to print author name

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


Above code works, but it is very hmm sensitive?
For example, I tried change this code to:

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

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


Results? Trying to get property of non-object error on line with this code.
Baybe I am skipping something simple but important. How to print URL or default value in blade view. Pseudo code what I mean:

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

Answer

Try

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

If this doesn't work (I haven't check it) try something like this:

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