Laravel unexpected redirects ( 302 )

I encountered an issue with 302 Redirects when posting ajax requests. The solution in this case was to remember to include the CSRF token.

See the Laravel 5.4 documents here: https://laravel.com/docs/5.4/csrf


I got the same issue and i solved it by adding the header with accept:'application/json'. And I think I checked the source code before which indicates that if you don't add this, it might redirect when you are using the auth middleware. But I am not sure if it is the case and I cannot recall where i found this.


After several hours of hair pulling, I have found my answer -- and it's silly.

The problem is that the route user.profile has a path user/{uid?} and it matches both user/logout and user/add as paths.

It being before the others, and not having a regex or similar, it handled the route.

I still don't know why a 302 was generated for that page, but found that moving it out of the AuthController and into the UserController (where it should be from the start) fixed the behavior.

Thus, my (amended and working) routes now look like so:

Route::group(['middleware' => 'web'], function () {
  // Authentication Routes...
  Route::get( 'user/login',  ['as' => 'user.login',     'uses' => 'Auth\AuthController@showLoginForm']);
  Route::post('user/login',  ['as' => 'user.doLogin',   'uses' => 'Auth\AuthController@login'        ]);

  Route::group(['middleware' => 'auth'], function() {
    // Authenticated user routes
    Route::get( '/',     ['as'=>'home', 'uses'=> 'HomeController@index']);
    Route::get( '/home', ['as'=>'home', 'uses'=> 'HomeController@home']);
    Route::get( 'user/logout', ['as' => 'user.logout',    'uses' => 'Auth\AuthController@logout'  ]);

    // *** Added /profile/ here to prevent matching with other routes ****
    Route::get( 'user/profile/{uid?}', ['as' => 'user.profile',   'uses' => 'UserController@profile' ]);
    Route::get( '/user/add',           ['as' => 'user.add',       'uses' => 'UserController@showAddUser']);

    [...]
    });
});

Tags:

Php

Laravel 5