3

I am using laravel 6 and I am currently using the following:

@if($randomNumb<0.5)
 // do sth
@endif

My problem with the above code snippet is that I pre-calculate the random number in the backend and then hand it to the blade template. Therefore, I get all the time the same random number, if I am using the above code-snippet more than one time in my blade-template.

Any suggestions how to calculate a unique random number directly in the @if-directive.

Appreciate your replies!

Carol.Kar
  • 4,581
  • 36
  • 131
  • 264

3 Answers3

2

There is nothing wrong with just calculating it right on the blade page each time you need it, especially if you need a unique value that would not have been passed from the controller.

@if(mt_rand(1, 100)  < 50)
    // do something
@endif
Watercayman
  • 7,970
  • 10
  • 31
  • 49
1

You can do like this:

@php
    $randomNum = rand(0, 99) / 10;
@endphp
@if($randomNum < 0.5)
 // do sth
@endif

You can read more here

I think it was helpful.

Good luck!

mare96
  • 3,749
  • 1
  • 16
  • 28
1

Use this multiple times,

@php

echo(rand(0,0.5));

@endphp