Before performing an action in Laravel 5.1

I write below code in the store and update method:

$v = Validator::make($request->all(), [ 'field' => 'required|max:100|min:5' ]); if ($v->fails()) { return redirect('route name') ->withErrors($v) ->withInput(); } 

Is there a built-in action method that is executed before any action is performed? if so, is this valid for an individual action or for a controller?

+5
source share
1 answer

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() { /* Validation code that will run for update_post action, and update_post ONLY*/ } public function validateCreateRequests() { /* Validation code that will run for create_post action, and create_post ONLY.*/ } 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

0
source

Source: https://habr.com/ru/post/1238072/


All Articles