4

Laravel – Route Matched Event

In Laravel there is a nice way to listen for many events, built-in and custom events, simply using code like this:

We can register event listeners. In Laravel documentation on their website, mentioned about Application Events and also about Custom Events (defined by user). There are also some special events available in Eloquent ORM known as Model Events and all these are very helpful for any application to organize operations using various events.

Laravel exposed these on the documentation with examples, discussed about every classes/objects and their methods and demonstrated their use cases nicely but there are also other useful public methods available that developers can use on many situations but those are not exposed or has not been discussed on the documentation.

To get a better idea about any tool/component or framework, a good documentation is necessary and Laravel has one and getting better day by day. In spite of this, there is another way to get much more better idea about any software component is reading it’s source code if possible. By reading the source code we may get a clean image of the whole process that a component does behind the scene. Sometimes you may find something interesting that is useful but not exposed and maybe you may develop another idea from this (by reading the source code) which may improve the software component by extending it and you may become a part of it by participating in the development (if it’s an open source project).

So, keeping this on mind, I often read the source code of any framework or software component to understand it deeply and while reading the source code of Laravel Framework version 4.1.19 (Illuminate\Routing\Router) I found something interesting and it’s about an event which is router.matched and it fires when a route match found from the route collection and it fires within dispatchToRoute() method of Router class and this class is available or exposed as Route (Using Route Facade). So, it’s possible to register an event listener to fire when any route matched for the current request and it happens before dispatching the route.

How to register an event listener for route.matched event:

It’s also possible to register a listener for this event this way:

Also this way as well:

In this callback function it’s possible to use any methods of Route (using $route/first parameter) and Request (using $request/second parameter), for example:

This is really a nice way to register a listener for the event when a route matches from the collection and it could be helpful. I’ve decided to post this article after I posted this answer on StackOverflow for a question, OP asked the same thing. Hope it could be helpful.

Latest Blog