Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ArchStanton's avatar

Blade - check if variable is being passed from controller

I am passing a variable from the controller

$data = array(
    'title'  => 'my title',
    'name' => 'John'
);

return View::make('mypage'')->with('data', $data);

Can I test if the variable exists? As name is not in every page and throws an error.

@if $data['name'] {{  $data['name'] }} @endif
0 likes
8 replies
usman's avatar
usman
Best Answer
Level 27

You can try something like:

@if( ! empty($data['name'))
    //
@endif

PS: please wrap your code in ~~~ to format code segments.

7 likes
bashy's avatar

Or if you need to do it inside a div or HTML element, do a shorthand if else

<a href="" class="{{ ( ! empty($data['name'] ? 'nameset' : 'namenotset') }}">
9 likes
DivisionB's avatar

Or you can simple use:

{{ $data['var'] or 'empty string' }}
14 likes
michaeldyrynda's avatar

If you want to check if the variable exists, use isset otherwise use empty if the variable will always be set and you want to determine if its value is falsey.

5 likes
MWDeveloper's avatar

I used this in my case and it works perfect.

<i class="{{ ( ! empty($message->attachment) ? 'fa fa-paperclip' : '') }}"

1 like
samhk222's avatar

@DIVISIONB - This will not work in all cases, for example, if i have an Carbon instance, and try to print this way, it will fail, because i can't call "format" on a null element

aeadedoyin's avatar

@USMAN -

@if(!empty($data['name']))
    //
@endif 

You missed a closing square bracket

Please or to participate in this conversation.