The built-in solution will be to use intermediaries, however, I see that you would like to execute this piece of code for certain actions.
If I were you, I would create a specific controller class that inherits all my controllers, and this controller would look something like this:
class FilteredController extends BaseController { private function getControllerAction(Request $request) { $action = $request->route()->getAction(); $controller = class_basename($action['controller']); list($controller, $action) = explode('@', $controller); return ['action' => $action, 'controller' => $controller]; } private function validateUpdateRequests() { } public function validateCreateRequests() { } public __construct(Request $request) { $route_details = $this->getControllerAction($request); if($route_details['controller'] == 'postsController') { if($route_details['action'] == 'update_post') { $this->validateUpdateRequests(); } else if($route_details['action'] == 'update_post') { $this->validateCreateRequests(); } } } }
Hope this helps.
Again , the best way is to use middlewares and use middlewares for certain actions, you will need to specify filtering in the routes, for example:
Route::get('/route_to_my_action', ' MyController@myAction ') ->middleware(['my_middleware']);
For more information about this filtering style in Laravel, visit docs
source share