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?

pupadupa
  • 1,530
  • 2
  • 17
  • 29

13 Answers13

98

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

@isset($var)

@endisset
sanchezcl
  • 1,210
  • 11
  • 6
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

Connor Leech
  • 18,052
  • 30
  • 105
  • 150
26

For Laravel 5.7 onwards use.

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

George John
  • 2,629
  • 2
  • 21
  • 16
21

For Laravel version >=5.7

{{ $value ?? '' }}

For Laravel version <5.7

{{ $value or '' }}
Puneet Verma
  • 1,373
  • 2
  • 19
  • 23
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

Ali
  • 752
  • 6
  • 18
  • 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 '16 at 21:16
16

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

 {!! !empty($myvariable) ? $myvariable : 'variable does not exist' !!}
TechPotter
  • 579
  • 8
  • 14
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') }}">
Dibyendu Mitra Roy
  • 1,604
  • 22
  • 20
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.

Kiran Maniya
  • 8,453
  • 9
  • 58
  • 81
5

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

Mr.Senhaji
  • 395
  • 5
  • 13
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')
Jeemusu
  • 10,415
  • 3
  • 42
  • 64
  • 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 '16 at 21:13
  • @pupadupa Have you passed the $subtitle variable to your view? Sounds like blade can't find your variable. – Jeemusu May 26 '16 at 02: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 '16 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 '16 at 02: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 '16 at 11:02
  • @pupadupa the problem is that that variable `$subtitle` doesn't exist. You NEED to pass this to your view from your controller. – Jeemusu May 29 '16 at 07:55
  • jeemusu@ hm... but why I could use not-existed variable in this way `{{ $checkvariable or 'not-exist' }}` but not in directive? I thought that there should be a way to create logics that check if variable not exist (inside directive) – pupadupa May 30 '16 at 22:24
  • Because blade checks to see if the `or` keyword exists, if it does then it doesn't throw an exception because you are passing it a default value. – Jeemusu May 31 '16 at 01:06
3

The @empty directive might be useful:

@empty($var)
   $var is unset or false-y
@endempty
crishoj
  • 5,660
  • 4
  • 32
  • 31
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; ?>";
    
});
JulianoMartins
  • 543
  • 1
  • 8
  • 19
  • 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 – Soy César Mora Jun 24 '22 at 13:49
0

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

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

rickslayer
  • 29
  • 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 '20 at 05:55