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

drissboumlik's avatar

loggin issue with ajax and laravel

Whey I login in laravel with ajax , i get success response, and after that i make a get request from the success section by calling a methode to fetch some shops data, then it redirect to the login page (like if I am not logged in) In postman this works perfectly even weather my routes are inside or outside the auth middleware ( I'm using external single html file instead of laravel views ) Here is my code : 1 - api.php

Route::post('login', 'Auth\LoginController@login');
Route::get('logout', 'Auth\LoginController@logout');
Route::post('register', 'Auth\RegisterController@register');
Route::group(['middleware' => 'auth:api'], function () {

    Route::get( 'shops/likedshops/', 'ShopUserController@liked_shopes' );

    Route::resource( 'shops', 'ShopController', [
        'except' => [
            'create',
            'store',
            'edit',
            'update',
            'destroy'
        ]
    ] );

    Route::resource( 'shopusers', 'ShopUserController', [
        'except' => [
            'create',
            'show',
            'edit',
            'destroy'
        ]
    ] );
});

2 : ShopUserController.php

<?php
 namespace App\Http\Controllers;
 use App\Jobs\DeleteDislikedShop;
 use Illuminate\Http\Request;
 use App\ShopUser;
 use App\User;
 use Auth;
 class ShopUserController extends Controller
 {
      // .... 
      public function liked_shopes(){
         $user_id = Auth::user()->id;
         $user = User::find($user_id);
         $shops = $user->shops()->where('is_liked', 1)->paginate(12);
         return response()->json(compact('shops'));
      }
  }

3 : app.js for my html file

$('.form-signin').on('submit',function (e){
    var email = $('#email-log').val()
    var password = $('#pass-log').val()       
    e.preventDefault(); 
    login(email, password); // <--------- Login
    return false;
});

function login(email, password) {
    $.ajax({
        method: 'POST',
        url: 'http://127.0.0.1:8000/login',
        data: {'email': email, 'password': password},
        success: function(response){
            localStorage.setItem('token', response.success.token);
            preferred_shops();  // <--------- Login
        },
        error: function(jqXHR, textStatus, errorThrown) { 
            alert('Email and/or Password Incorrect');
            console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
        }
    });
}
function preferred_shops(page_number = 1) {
    $('#preferred-shops').remove();
    $('#nearby-shops').remove();
    $.ajax({
        method: 'GET', 
        url: 'http://127.0.0.1:8000/shops/likedshops',
        data: {'page' : page_number},
        headers: {"Authorization": localStorage.getItem('token')}, // This isn't helping
        success: function(response){
            var data = response.shops.data;
        },
        error: function(jqXHR, textStatus, errorThrown) { 
            console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
        }
}

4 - I added this in VerifyCsrfToken class

protected $except = [
        'stripe/*',
        'http://127.0.0.1:8000/*',
    ];
0 likes
4 replies
Guru5005's avatar
Guru5005
Best Answer
Level 3

Try these headers if u are using middle ware api and laravel passport for authentication

headers: {
        Authorization: "Bearer " + token,
        Accept: "application/json"
      }
Guru5005's avatar

Okay than what are you using for authentication?? It totally depends upon Your authentication, as the GET request does not have the specified data or other parameters like headers, cookie etc, the request is not getting authenticated hence redirecting to login page. Try to debug like

console.log(response)

drissboumlik's avatar

I ended up using passport, and cleared the cache , Thanks for your answer

Please or to participate in this conversation.