Jijo John
Jijo John

Reputation: 1375

How laravel handles same get routes

I am building a custom routing system for my home grown framework. My question is how laravel handles same routes in their routing system. for example

Route::get('api/users/{user}', function (App\User $user) {
    return $user->email;
});

Route::get('api/user/{pass}', function (App\User $user) {
    return $user->email;
});

the number of the arguments in the route api/user/{pass} & api/users/{user} are same. How they do this ?. How they differentiate the routes ?. How the matching process works ?.

Upvotes: 0

Views: 319

Answers (2)

Asur
Asur

Reputation: 4017

Laravel looks for routes secuentially, this means given two routes with the same endpoint, it will always call the first one found and stop there, so the second one it will never be reached, for example:

// Your url is user/johndoe

// It will start looking for a match

Route::get('user/{name}', function ($name) { // This route is a match 
    // This callback is called and Laravel stops searching
    return $name;
});

Route::get('user/{id}', function ($id) { // This route is also a match
    // But a callback is already been called so this one is never reached
    return $id;
});

In case you want to differentiate both routes you can do so using regex:

Route::get('user/{name}', function ($name) {
    // This callback will only be executed when a word is passed in
})->where('name', '[A-Za-z]+');

Route::get('user/{id}', function ($id) {
    // This callback will only be executed when a number is passed in
})->where('id', '[0-9]+');

As you can see, both of this routes have the same endpoint, but now they will filter the parameter given according to the regex you provide. Hope this helps you.

Upvotes: 2

coder_1432
coder_1432

Reputation: 283

Laravel will take the first route of the two only, since they are basically the same. It has no way to differentiate the two routes. If one of the routes method would be different (i.e put or post instead of get) then both routes would work. –

Upvotes: 0

Related Questions