Search code examples
javascriptphpreactjslaravellaravel-passport

Laravel : Get id from localstorage


I have an application using for backend Laravel and in frontend React.

In React, to retrieve the data of the logged user I use :

   const user = JSON.parse(localStorage.getItem("userData"));

In laravel's web.php to get the logged user_id I use Auth::user()->id.

Since I'm using React for authentification and Laravel to serve the APIs, I can't use Auth::user()->id directly to read the logged user's id in JS.

I understand that I can't pass directly localstorage as it's something stored locally in the browser. I tried setting a token for the logged user using Laravel Passport and it's working. But how to retrieve the data of the logged user in web.php or a Controller ?


Solution

  • You can use Laravel Sanctum. Doc

    In Laravel Sanctum your application use session & cookies instead of tokens for user authentication. So you can retrieve user data anywhere you want.