56

I'm trying to create blade directive which echo variable (if variable defined) or echo "no data" if variable undefined.

This is my code in AppServiceProvider.php:

<?php

namespace App\Providers;

use Blade;
use Illuminate\Support\ServiceProvider;


class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Blade::directive('p', function($ex) {
            error_log(print_r($ex,true));
            return '<?php $defined_vars = get_defined_vars(); if(array_key_exists(\''. $ex .'\', $defined_vars) ): echo ' . $ex . ' ; else: echo \'no data\'; endif;?>';
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Here is my index.blade.php:

<p class="lead">@p($myvar)</p>

But my directive "p" gives "no data" if variable defined. If I use isset error occurres: Cannot use isset() on the result of an expression (you can use "null !== expression" instead)

How could I check inside directives if variable defined?

1
  • So you're saying if(isset($myvar)) doesn't work?
    – Can Celik
    May 25, 2016 at 1:33

13 Answers 13

98

Blade has a directive to check if a variable is set:

@isset($var)

@endisset
2
  • 4
    how do you handle else? Feb 13, 2020 at 9:40
  • 7
    Like normal with an @else
    – dsturbid
    Apr 9, 2020 at 10:32
33

Try checking if the variable is empty:

@if(empty($myvar))
    <p>Data does not exist</p>
@else
    <p>Your data is here!</p>
@endif

Can also check this thread

26

For Laravel 5.7 onwards use.

{{ $checkvariable ?? 'not-exist' }}

1
  • Not true, I'm getting Undefined Variable with this code, using Laravel v7
    – Lewis
    Apr 6, 2022 at 7:58
22

For Laravel version >=5.7

{{ $value ?? '' }}

For Laravel version <5.7

{{ $value or '' }}
0
19

You can use in Blade functionality for checking isset i.e

{{ $checkvariable or 'not-exist' }}

https://laravel.com/docs/5.2/blade#displaying-data

1
  • 1
    In future I want to add more complex logics to my directive. For example different style for auth user. So I want just type p($foo) in view instead of repeating {{ $checkvariable or 'not-exist' }} and logics for auth check.
    – pupadupa
    May 25, 2016 at 21:16
16

The best and cleanest way check if a variable exists in blade:

 {!! !empty($myvariable) ? $myvariable : 'variable does not exist' !!}
1
  • I had an undefined index in an array and this was the perfect solution.
    – Chad
    Oct 13, 2018 at 4:24
6

You can do it in few different ways.

Sample-1:

@if( !empty($data['var']))
   {{ $data['var'] }} 
@endif

Sample-2:

{{ $data['var'] or 'no data found' }}

Sample-3: Using ternary operator

<a href="" class="{{ ( ! empty($data['var'] ? $data['var'] : 'no data found') }}">
6

You can use the @isset blade directive to check whether the variable is set or not. Alternatively, if you have the default value for that variable you can directly use it as {{ $vatiable ?? 'default_value' }}. The ?? way is available in Laravel v5.7 onwards.

If you want to check for multiple variables at once, you can do it by applying AND operation to expression as @if(isset($var_one) && isset($var_two)).

There are also other ways (lengthy) using @if directive as @if(isset($variable)) but it's not recommended.

Some developer uses @ symbol for error control in a similar situation. The at-sign (@) is used as error control operator in PHP. When an expression is prepended with the @ sign, error messages that might be generated by that expression will be ignored. If the track_errors feature is enabled, an error message generated by the expression and it will be saved in the variable $php_errormsg. This variable will be overwritten on each error. The use of @ is very bad programming practice as it does not make the error disappear, it just hides them, and it makes debugging a lot worse since we can’t see what’s actually wrong with our code.

5

For the last version of Larvael make the variable optional in the blade template. Replace $myvar with {{ $myvar }} with {{ $myvar?? '' }}

3

What are you trying to pass to your custom directive? If it's just a string/int the following should work.

Blade::directive('p', function($expression){
    $output = $expression ? $expression : 'nodata';
    return "<?php echo {$output}; ?>";
});

In Blade Template

@p('Foo')
8
  • I want to use it like that @p($subtitle) in my view. And If I use your solution I got this error: Undefined variable: subtitle
    – pupadupa
    May 25, 2016 at 21:13
  • @pupadupa Have you passed the $subtitle variable to your view? Sounds like blade can't find your variable.
    – Jeemusu
    May 26, 2016 at 2:40
  • this is the problem - check in directives if variable doesn't exist. Is there a way to return 'nodata' from directive, if I didnt pass variable to view?
    – pupadupa
    May 26, 2016 at 20:35
  • No, I would assume the error you are receiving is from blade before it even executes the custom directive.
    – Jeemusu
    May 27, 2016 at 2:12
  • jeemusu@ it appears in view Undefined variable: subtitle (View: lp/resources/views/blocks/cover.blade.php) (View: lp/resources/views/blocks/cover.blade.php)
    – pupadupa
    May 27, 2016 at 11:02
3

The @empty directive might be useful:

@empty($var)
   $var is unset or false-y
@endempty
1

To check if variable exist in Laravel blade directive, do this:

Blade::directive('datetime', function ($value) {
    
    return "<?php echo isset($value) ? ($value)->format('d/m/Y H:i:s') : null; ?>";
    
});
1
  • Is there a way to retrieve the value of "$value" automatically without having to pass it from the render. For example just use @something and in the creation of the directive rescue $something Jun 24, 2022 at 13:49
0

If you trying check a bool variable you can use @unless

<input type="text" class="@unless ($variable) d-none @endunless" >

1
  • The question is about existence of the variable, not the boolean value. @unless will fail if the variable is not set.
    – datashaman
    Jan 27, 2020 at 5:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.