Search code examples
phplaravellaravel-5routeslaravel-middleware

Laravel route group and middlewares


i am working on a laravel project with users who can have status verified (email verified).

on the other hand, users can have a subscription which is verified by a "subscriptions" middleware.

So I have several groups of routes including 2 of which the only difference is the presence of subscription or not

group 1:

Route::group(['middleware' => ["auth:sanctum", "verified"]], function () {}

group 2

Route::group(['middleware' => ["auth:sanctum", "verified", "subscriptions"]], function () {}

my question is about the order laravel uses for routes in these groups. for example if the user satisfies all the middleware of the first group, does laravel test the middleware of the second? Does a user verified have a chance to enter the second group of routes with subscription?

conversely, if the user does not have a subscription, he will not pass the subscription middleware. but I have the impression that the user is redirected by the subscription middleware which fails while laravel could find the right route in the group without this middleware (group 1)

what I would like is that it just tests for the presence of a subscription and that if it does not find one it looks for the route in group1.

Does the order of the groups in the code have an impact on the processing?

thanks.

edit:

Route::group(['middleware' => ["auth:sanctum", "verified", ]], function () {
            Route::get("/new", function () {
               // redirect to payment
            })->name("new-payment");
    }


Route::group(['middleware' => ["auth:sanctum", "verified", "subscriptions"]], function () {
    Route::get("/new", function () {
        return view("bourse-new");
    })->name("new-abo");

it is the same route but with a different behavior depending on the presence or not of a subscription When subscriptions middleware fails, it's redirect to "home", but i want laravel to use the first route


Solution

  • thanks to @NoobDev.

    I took over his solution by integrating the subscription tests into middleware

    Route::group(['middleware' => ["auth:sanctum", "verified"]], function () {
        Route::get("/new", function () {
            return view("bourse-new");
        })->middleware("subscriptions")->name("bourse-new");
    });
    

    and the subscriptions middleware:

    public function handle(Request $request, Closure $next){
        if( //logic tests) {
             return $next($request);
         }
         return redirect('/checkout'); //redirect to payment
    }
    

    this solution is almost perfect, thanks everyone