While working with web applications, there are several times when we need to perform or execute something just before each controller’s action is called. I have seen many scenarios where we need to check for something very common each time.

What we need to achieve

Recently, while working with an application in PHP using Laravel framework, we had a similar situation.

  • We need to set the organization_id in session just before the action code execution starts so that we can easily read organization from session and return the data accordingly.
  • Perform some basic access control validation on the authenticated user in the system

Not to forget, the solution must be optimized and can be easily manageable.

What we tried, but didn’t worked 🙁

  • We tried to use the approach of inheritance where all my controllers extend BaseController and tried to put the logic in the __construct() of BaseController but unfortunately session was not available in the construct.
  • We read couple of articles where great minds were suggesting to use Middleware. The challenge with middleware was that, sessions is not available by default. so you can not perform anything on authenticated user. There were various workaround suggested, like to use the StartSession or AuthenticateSession middleware by default. But there were some caution around it and few people was not in the agreement on the same. so we dropped it.

We lived with a clever way that worked but not a good solution 🙂

We created a custom function LoadMetadata() in the BaseController that is extended by my all controllers and we called this function explicitly at the start of each controller’s action.

Okay, Great we achieved what we wanted but not satisfied the way we did, as other programmers have to remember to call this function in each action otherwise a fail.

Finally, the best way to do so found 😌

Laravel is an amazing framework, you can overrides almost everything, you just need to get into little deep.

Laravel first calls a function callAction to execute the controller’s method in each request and this is exactly the place we were looking for. We can inject our function call inside this. All you need to override the function in BaseController. The good part is that you have access to session, route, requests everything.

Here is the final solution. Need to remove manual call from each controller’s action and put it as single place inside callAction function by overriding in BaseController.  After this change, every time a controller’s method is invoked from defined routes “LoadMetadata()” function calls automatically and any validation, if any.

 

 

 

1 thought on “Laravel: Call a routine or function before each route action is called

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.

Back To Top