online software programming courses

Laravel Controller Send Value to JavaScript

In this tutorial I will show you how to send value from controller to Javascript in Blade in Laravel application.

Say you have a value $x=10 in your controller and you want to grab the value in your blade. Then do the following steps to get the value in front end code.

1. Send the value using compact function to blade like below

public function Posts(){
    ....................
    .....................
    $x=10;
   ......................
   return view('my_view', compact('x'));
}

2. Now in your javascript retrieve the value like below

<script>
  let x = "{{$x}}";
  /*
    Now you can print it or use the way you want.
  */
  console.log(x);
<script>

3. In the above javascript function $x has the value passed from laravel controller.