Reputation: 1384
In Laravel blade you can do:
{{ $variable or 'default' }}
This will check if a variable is set or not. I get some data from the database, and those variables are always set, so I can not use this method.
I am searching for a shorthand 'blade' function for doing this:
{{ ($variable != '' ? $variable : '') }}
It is hard to use this piece or code for doing this beacuse of, I do not know how to do it with a link or something like this:
<a href="{{ $school->website }}" target="_blank">{{ $school->website }}</a>
I tried:
{{ ($school->website != '' ? '<a href="{{ $school->website }}" target="_blank">{{ $school->website }}</a>' : '') }}
But, it does not work. And, I would like to keep my code as short as possible ;)
Can someone explain it to me?
UPDATE
I do not use a foreach because of, I get a single object (one school) from the database. I passed it from my controller to my view with:
$school = School::find($id);
return View::make('school.show')->with('school', $school);
So, I do not want to make an @if($value != ''){}
around each $variable (like $school->name).
Upvotes: 25
Views: 53171
Reputation: 18117
From Laravel 5.4, you can also use the @isset directive.
@isset($variable)
{{-- your code --}}
@endisset
https://laravel.com/docs/9.x/blade#if-statements
Upvotes: 0
Reputation: 1507
I wonder why nobody talked about $variable->isEmpty()
it looks more better than other. Can be used like:
@if($var->isEmpty())
Do this
@else
Do that
@endif
Upvotes: 1
Reputation: 751
With php 7, you can use null coalescing operator. This is a shorthand for @m0z4rt's answer.
{{ $variable ?? 'default' }}
Upvotes: 9
Reputation: 41051
I prefer the @unless
directive for readability in this circumstance.
@unless ( empty($school->website) )
<a href="{{ $school->website }}" target="_blank">{{ $school->website }}</a>
@endunless
Upvotes: 15
Reputation: 694
{{ ($school->website != '' ? '<a href="{{ $school->website }}" target="_blank">{{ $school->website }}</a>' : '') }}
change to
{{ ($school->website != '') ? '<a href="' . $school->website . '" target="_blank">' . $school->website . '</a>' : '' }}
or the same code
{{ ($school->website != '') ? "<a href='$school->website' target='_blank'>$school->website</a>" : '' }}
Upvotes: 6
Reputation: 2784
try this:
@if ($value !== '')
{{ HTML::link($value,'some text') }}
@endif
Upvotes: 22