Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Whats the difference between these two route api approach

This

Route::middleware(['cors'])->group(function () {

    Route::post('/login', 'AuthController@APIstore');

    Route::middleware(['auth:api'])->group(function () {

        Route::post('/logout', 'AuthController@APIdestroy');

        Route::get('/projects', 'ProjectController@getAll');

    });

});

And this

Route::group(['middleware' => 'cors'], function() {

    Route::post('/login', 'AuthController@APIstore');

    Route::group(['middleware' => 'auth:api'], function() {

        Route::post('/logout', 'AuthController@APIdestroy');

        Route::get('/projects', 'ProjectController@getAll');

    });

});

On the first code, CORS middleware works with /login but does not work for /logout and /projects

On the second code, the CORS middleware does not work at all

is there a reason behind this?

like image 540
Roi Avatar asked Jan 18 '26 19:01

Roi


1 Answers

So, as per the Laravel Routing Doc, the top level middleware is applied to all groups in the group. So using Route::middleware(['cors']) will mean this middleware will be applied to Route::middleware(['auth:api']).

However Route::group(['middleware' => 'cors'] is a group route not a middleware route, so the middle is not applied to child groups.

like image 67
Lewis Johnson Avatar answered Jan 21 '26 09:01

Lewis Johnson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!