Check if variable exist in laravel's blade directive
Asked Answered
R

13

58

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?

Retha answered 25/5, 2016 at 0:25 Comment(1)
So you're saying if(isset($myvar)) doesn't work?Wiretap
P
104

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

@isset($var)

@endisset
Poetaster answered 28/9, 2018 at 20:30 Comment(2)
how do you handle else?Finespun
Like normal with an @elseBundesrat
H
35

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

Hamsun answered 3/11, 2017 at 16:3 Comment(0)
G
28

For Laravel 5.7 onwards use.

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

Guidotti answered 18/10, 2018 at 12:19 Comment(1)
Not true, I'm getting Undefined Variable with this code, using Laravel v7Latria
D
24

For Laravel version >=5.7

{{ $value ?? '' }}

For Laravel version <5.7

{{ $value or '' }}
Duncandunce answered 6/7, 2019 at 16:13 Comment(0)
P
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

Petrochemistry answered 25/5, 2016 at 7:13 Comment(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.Retha
B
16

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

 {!! !empty($myvariable) ? $myvariable : 'variable does not exist' !!}
Brittan answered 5/7, 2018 at 8:7 Comment(1)
I had an undefined index in an array and this was the perfect solution.Fronniah
G
7

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.

Granulite answered 3/12, 2019 at 7:54 Comment(0)
C
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') }}">
Congenital answered 8/1, 2019 at 9:40 Comment(0)
C
5

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

Cetane answered 17/6, 2020 at 21:21 Comment(0)
W
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')
Whip answered 25/5, 2016 at 2:5 Comment(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: subtitleRetha
@Retha Have you passed the $subtitle variable to your view? Sounds like blade can't find your variable.Whip
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?Retha
No, I would assume the error you are receiving is from blade before it even executes the custom directive.Whip
jeemusu@ it appears in view Undefined variable: subtitle (View: lp/resources/views/blocks/cover.blade.php) (View: lp/resources/views/blocks/cover.blade.php)Retha
@Retha the problem is that that variable $subtitle doesn't exist. You NEED to pass this to your view from your controller.Whip
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)Retha
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.Whip
M
3

The @empty directive might be useful:

@empty($var)
   $var is unset or false-y
@endempty
Ment answered 2/1, 2019 at 0:32 Comment(0)
A
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; ?>";
    
});
Abductor answered 16/8, 2020 at 18:3 Comment(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 $somethingCaxton
A
0

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

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

Arthurarthurian answered 8/11, 2019 at 13:48 Comment(1)
The question is about existence of the variable, not the boolean value. @unless will fail if the variable is not set.Autry

© 2022 - 2024 — McMap. All rights reserved.