Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

tb's avatar
Level 1

Get Controlller Name and Action in Middleware

Hi,

I'm working on a new project builds with Laravel 5. I'm trying to display on each blade templates a variable with the controller name and the action name. Example :

<body class="{{ $body_class }}">

I've created a middleware, i can set my variable but it's impossible to get the current request controller and action. Someone know how to do it ?

0 likes
6 replies
bestmomo's avatar

Use in your middleware :

$request->route()->getAction();

You'll get all informations you need.

1 like
kamleshcgtechno's avatar

Getting error - Call to a member function getAction() on null (500 Internal Server Error). Any suggestion?

pmall's avatar
pmall
Best Answer
Level 56

Don't use a middleware for this.

If you want to send variables to many views use a View Composer.

Every time you want to share some logic and variables to a set of view, use a view composer. Middleware purpose is to act on the request.

tb's avatar
Level 1

Thank's pmall, it's the solution ! Now, it's work. Could you explain me the difference between Service Provider and Middleware ? (In french please :D)

pmall's avatar

Il n'y a absolument rien à voir entre un middleware et un service provider.

Les middleware sont des sorte de "filtre" qui s’exécutent dans un ordre précis pour modifier la requête. Par exemple pour définir la locale courante. Certains peuvent être exécutes avant la requête, d'autre après.

Un service provider peut servir a plein de choses, pour la configuration. Par exemple, assigner une vue à un view composer ;). Mais aussi associer des instances concrètes d'une classe à une interface, etc... (ex : l’implémentation concrète d'un repository).

tb's avatar
Level 1

Merci beaucoup, j'ai enfin compris !

Please or to participate in this conversation.