Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

The beginner's avatar

Get Auth::user()->id in javascript

Hi,

I'm working with laravel 8, and i'm trying to get the id of the authenticate user in my javascript but i don't know how to do it.

If someone can help me...

Thanks.

0 likes
7 replies
tykus's avatar

Pass the data to Javascript in your Blade template:

<script>
  window.userID = {{ auth()->id() }};
</script>

Now you have a userID property on the window Object. You could, of course, define a different structure if your app needs other data shared from PHP, but the general idea would be the same.

This is a Laracasts package that was the subject of a video tutorial a number of years ago - it supports Laravel 8; but it should not be necessary unless you are passing a lot of data dynamically to the frontend:

https://github.com/laracasts/PHP-Vars-To-Js-Transformer

1 like
The beginner's avatar

@tykus Thanks for your reponse sir, but I've already tried this.

I put this code in one of my views (in the script tag) and when i go to my bootstrap.js file and I console.log() my window object, i don't find my property.

In other words, if i do that :

console.log( window.userID )

I'll get an undefined.

tykus's avatar
tykus
Best Answer
Level 104

It depends on where the scripts are relative to each other in the DOM.

1 like
martinbean's avatar

@the beginner Why are you trying to get sensitive server-side data like the authenticated user, into your JavaScript? What are you wanting to do with the authenticated user object once you have it?

1 like
Sinnbeck's avatar

@The beginner if you send it to the backend again, then just use the backend to get it again using auth()

1 like

Please or to participate in this conversation.