Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4.2 blade: check if empty

Tags:

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).

like image 325
Marten Avatar asked Dec 15 '14 14:12

Marten


People also ask

IS NOT NULL in Laravel if condition?

Check if not null: whereNotNullSELECT * FROM users WHERE last_name IS NOT NULL; The equivalent to the IS NOT NULL condition in Laravel Eloquent is the whereNotNull method, which allows you to verify if a specific column's value is not NULL .

How do you check if a variable is set or not in Laravel blade?

You can use the @isset blade directive to check whether the variable is set or not.


2 Answers

try this:

@if ($value !== '')     {{ HTML::link($value,'some text') }} @endif 
like image 63
soroush gholamzadeh Avatar answered Oct 18 '22 08:10

soroush gholamzadeh


I prefer the @unless directive for readability in this circumstance.

@unless ( empty($school->website) )     <a href="{{ $school->website }}" target="_blank">{{ $school->website }}</a> @endunless 
like image 20
Jeff Puckett Avatar answered Oct 18 '22 07:10

Jeff Puckett