Mohamad Amirul
Mohamad Amirul

Reputation: 53

convert ternary operator to if else in laravel

I've created posts table and display on interface post table. so I want to display the owner of the post by using thier name. the first step is I use ternary operator but I want to change to if else statement. But If try second way will get the error:

syntax error, unexpected '{' (View:.

how the correct way If I want to use the second way.

First way

<td>{{ isset($post->user) ? $post->user->name : '' }}</td>

Second Way

<td>
    @if(isset($post->user)
    {
        $post->user->name;
    }
    else
    {
        '';
    });
    @endif
</td>

Upvotes: 0

Views: 320

Answers (1)

lagbox
lagbox

Reputation: 50501

@if (...) gets compiled to <?php if (...): ?>. So you are no longer in the context of PHP tags between the Blade directives.

You can do this simply by using Blade though:

@if(isset($post->user))
    {{ $post->user->name }}
@endif

--- which is basically:

<?php if (isset($post->user)): ?>
    <?php echo e($post->user->name); ?>
<?php endif; ?>

There is no need for the else branch here with your example.

Alternative:

{{ $post->user->name ?? '' }}

Upvotes: 1

Related Questions