Adam Mańkowski Adam Mańkowski - 11 months ago 40
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' }}



{{ 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>