Adam Mańkowski Adam Mańkowski - 1 year ago 103
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 Source


{{ 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>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download