Laravel Controller Send Value to JavaScript

Created At: 2020-12-25 20:51:39 Updated At: 2020-12-25 21:01:11

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.

Comment

  • r
    ra2886380@gmail.com

    2024-10-24 11:34:16

    dddd

Add Reviews