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
Your
@if(randomHero === 1)
@include('components.Hero1')
@else
@include('components.Hero2')
@endif
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
const randomHero = randomNumber(1, 2);
is being executed much later. You will need to randomize, using the rand function of PHP, like
$randomHero = rand(0, 1);
Then you can pass this to your view:
public function render()
{
return view('index', ['randomHero' => rand(0, 1)]);
}
and make sure that before the script that you defined you embed another script, like
<script>
var randomHero = {{ randomHero }};
</script>