Michael
Michael

Reputation: 509

Elegant way for quick IF statement in blade

I´m new to Laravel and I know I can echo variables within double curly brackets like this:

<p>{{ $posts->id }}</p>

Now in my case I have a form that sometimes contains the variable $posts (which is the table by the way) to update and sometimes doesn´t contain it to insert a row depending on the parameters in the URL.

Of course if there is no post then the part "->id" will fail. Is there an elegant way to make a quick IF statement here, like:

<?php if ($posts) echo $posts["id"]; ?>

but just using the blade engine.

I know I can use @if around the HTML-block but then I would have to write that block twice all the time.

Upvotes: 1

Views: 5480

Answers (2)

jes490
jes490

Reputation: 41

Another and more "laravel-like" way to do it is optional helper.

{{ optional($posts)->id }}

Works great in conjuration with old helper.

Upvotes: 1

Alexey Mezenin
Alexey Mezenin

Reputation: 163758

It depends on what exactly is $posts.

You can use ternary statement. For example, if $posts is collection or array, use empty:

{{ empty($posts) ? '' : $posts->id }}

If it's just variable, use isset()

In some cases can use or syntax:

{{ $posts or 'It is empty' }}

In PHP7 you can use ?? (null coalescing operator) to check if variable isset(). For example:

{{ $posts ?? $posts->id }}

You can see another explanation in the official documentation (see Echoing Data If It Exists part).

Upvotes: 8

Related Questions