Laravel 5 Blade Custom Directive - trouble passing variable
Asked Answered
C

2

6

I am trying to create a Blade directive that will set a class on my table row depending on what gets passed in. The problem is that when I call it, the value of the variable is not being passed in - the literal string that I have between the parenthesis is.

In my view:

@row($inspection->inspection_disposition)

In the directive:

 Blade::directive('row', function($data)
    {
        var_dump($data);
           .
           .
           .
     }

What I see in the dump is:

string(37) "($inspection->inspection_disposition)"

Shouldn't I see the value of that variable? That's what I want. What am I missing here?

MORE INFO:

I need to use the value of that variable in the directive, like this:

if($data == "hello")
{
   return something
}
elseif($data == "goodbye")
{
   return something else
}

This is a simplified example, but hopefully it will help to illustrate that I need to compare the value of the variable inside the directive, then determine what to do. Perhaps I need to use eval() ?

Civilize answered 5/4, 2016 at 19:58 Comment(2)
I've been trying to use eval() but I don't think that's right... Why doesn't this pass the value into the directive????Civilize
I am struggling with the same problem, I just can't pass evaluated string or variable to my custom Blade directive. It looks like , by design, it's meant to be evaluated only after a return. eval() is always dangerous approach, though.Versatile
S
3

Blade directive should return a string that php will interprete, like this:

Blade::directive('row', function($data)
{
    return "<?php var_dump($data); ?>";
}
Shaver answered 5/4, 2016 at 20:12 Comment(1)
Ok - I understand that now. Thank you. I will update my question to better explain what I am doing.Civilize
N
0

Here's the secret:
It's not pass by value or pass by reference it's kind of like pass by variable name.

So think of it this way:
When you call:

@row($data)

imagine that you are calling:

$row('$data')   /* Don't actually do this */

Because that's how essentially laravel processes it. It's going to take the names of the variables you pass and insert them into the php code that you return to the view.

So like @RDev's answer, place the following (in the boot() function of app\Providers\AppServiceProvider.php):

Blade::directive('row', function($parameter)
{
    return "<?php var_dump($parameter); ?>";
}

The $data variable will hold this literal value that you passed it "$data". And it will swap that into your php code like so:

<?php var_dump($data); ?>

And then that php code will get inserted into your view in place of the @row blade directive.

Northampton answered 2/5, 2021 at 15:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.