How to access PHP variables in JavaScript using Laravel?

Sometimes, we pass data from PHP to JavaScript through variables or functions to perform actions. Because PHP brings data from the server and JavaScript handles on the client side.

Let’s suppose, on the page load, you want to make an ajax request that needs a user’s primary id. Obviously, you will need PHP’s help to fetch the user’s primary id through the session. So here you will need to fetch the user id through PHP and then pass it into JavaScript to send it with the request.

Let’s see an example in which we will be passing data from controller to view for accessing in JavaScript. In the profile controller, we have an index method that loads the profile blade file from the resources/views directory and also passes data.

class ProfileController extends Controller
{
    public function index()
    {
        $userId = 20;

        return view('profile', ['userId' => $userId]);
    }
}

In this index method, we have a static value assigned to the $userId variable that passes to the profile blade through Laravel’s view() function. This is up to you if you want to pass a dynamic value or static from the controller.

Next, let’s access the $userId variable in JavaScript. Add the below script into the profile blade that is located in the resources directory.

<script>
    let userId = '{{ $userId }}';
    console.log(userId);
    // Output: 20
</script>

In this script, we are echoing PHP variable $userId into JavaScript through double curly braces. In double curly braces, we have a PHP variable whose value is assigned to JavaScript variable userId that has the let keyword. It is equivalent to below

let userId = <?php echo $userId; ?>;
console.log(userId);
// Output: 20

Following is complete code from profile.blade.php

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Access PHP variables in JavaScript using Laravel</title>
    </head>
    <body>
        <script>
            let userId = '{{ $userId }}';
            console.log(userId);
        </script>
    </body>
</html>

Conclusion

To access PHP variables into JavaScript in Laravel, you will need to pass data from the controller to view and then access through double curly braces.