Home > Software engineering >  How does laravel parse routes into component parts?
How does laravel parse routes into component parts?

Time:11-12

It became curious, how does laravel parse routes and understand which route to match with the correct url? For example url be processed by the appropriate route?

www.ru/post/100/comments/500

Route::get('/posts/{post}/comments/{comment}', [NameConroller::class, 'show']);

At first glance,

  1. it seems that we should split the incoming route (for example explode()) by /.
  2. Then find all routes where the first part starts with /post
  3. From the routes found in the previous paragraph, we should understand (how?) that /{post} matches any number. Etc.

Perhaps someone dug into the source code or just knows how it works? It would be interesting to know)

CodePudding user response:

It all happens here https://github.com/laravel/framework/blob/9.x/src/Illuminate/Routing/RouteCollection.php#L153

Laravel loops through all your routes until it find a match which is checked here https://github.com/laravel/framework/blob/9.x/src/Illuminate/Routing/Route.php#L328

If you look at https://github.com/laravel/framework/blob/9.x/src/Illuminate/Routing/Matching/UriValidator.php you would see that /posts/{post}/comments/{comment} gets compiled to {^/posts/(?P<post>[^/] )/comments/(?P<comment>[^/] )$}sDu and it checked with regex

For an explanation on the regex look here https://regex101.com/r/VgsiHI/1

The first url to match is the route that gets the request

  • Related