Hi I’m brand new to Laravel and Blade (and kind of beginner to PHP) but not JS, so I’ve found how to do @if
@else
statements and I have an external .js
file with a simple script that is returning a random number between 1 or 2 for now.
script.js
function randomNumber(min, max) {
return Math.floor(Math.random() * ((max + 1) - min) + min);
}
const randomHero = randomNumber(1, 2);
console.log(randomHero);
Then in the blade.php
file I’m trying to check if the random number stored in the variable randomHero
is either 1 or 2 with an if/else statement:
index.blade.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Homepage</title>
<link href="{{asset('css/style.css')}}" rel="stylesheet">
</head>
<body>
<section id="main">
@if(randomHero === 1)
@include('components.Hero1')
@else
@include('components.Hero2')
@endif
</section>
</body>
<script src="{{ asset('js/script.js')}}"></script>
</html>
However I keep getting the error Undefined variable randomHero
so I’m guessing I’m either missing a step for passing the variable from the .js
file into the blade
file to use or I’m calling the varibale incorrectly?
Any help would be much appreciated thanks
2
Answers
Your
is being executed on the server while the page is being generated and then it’s sent to the browser, i.e., the client-side, where your
is being executed much later. You will need to randomize, using the rand function of PHP, like
Then you can pass this to your view:
and make sure that before the script that you defined you embed another script, like
You can achieve this otherwise by calling the php rand function straight away from your blade file rather than defining js method to do this. It would be as shown below;