2
votes

I am using Laravel Framework 6.20.12 and PHP 7.4.1.

I have created a custom blade directive:

        $blade->directive('randomValFromArr', function ($expression) {
            return '<?php $array=' . $expression . '; $val = array_rand($array, 1); echo $array[$val]; ?>';
        });

This directive basically, chooses a random value from an array of values and outputs it.

If I use this 2 times in my *.blade.php file I get for both functions the same array output or in other words the same key:

@randomValFromArr(["1", "2", "3", "4"])

@randomValFromArr(["1", "2", "3", "4"])

{{--
OUTPUT:

1
1
--}

It seems to me that the blade engine computes the directive once and then uses it within the template.

Any suggestions how to really get a random value or unique value for each occurrence of my @randomValFromArr-functionm like:

@randomValFromArr(["1", "2", "3", "4"])

@randomValFromArr(["1", "2", "3", "4"])

{{--
OUTPUT:

3
1
--}

I appreciate your replies!

1
One approach could perhaps be storing the array in the user's session after removing the randomly generated value. - Remy

1 Answers

1
votes

Blade will compute the directive each time it is called; otherwise, how could we pass in parameters, what if you passed in different arrays?

I tested your code and it worked as expected.