John Davidson

php - Login user in whole laravel system - web and api


I have a big problem (for my self)

we have a laravel project that some pages with livewire and laravel blade (auth with session) and some other with react and API (passport bearers token)

user login with API in react page and logged in panel
but I have problem to login user in laravel web guard

I make a middleware

 $apiKey = $request->bearerToken();
$user = request()->user();
if(!empty($user) && !auth()->guard('web')->check()) {
Auth::guard('web')->login($user, true);

but I think this is bad practice

what can i do?

site structure is like this:

--login page with react and API

---- user dashboard with react and API

---- user ticket system with livewire and laravel blade file (session)

---- user QA system with livewire and laravel blade file (session)

My Answer:

if ($apiKey) {
$user = User::where('api_token', $apiKey)->first();

if ($user) {

return $next($request);

This middleware checks if the Authorization header is present in the request and if it is, it tries to find a user with the corresponding API token. If a user is found, it logs them in using the Auth::login() method.

You can then apply this middleware to your web routes to ensure that users are logged in when accessing those routes, even if they initially logged in through the API in your React application.

Hope this helps! Let me know if you have any further questions.

Rate this post

3 of 5 based on 7999 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us