Before executing Action in Laravel 5.1

随声附和 提交于 2020-01-13 09:18:08

问题


I am writing the below code in 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 any inbuilt action method that executes before executing any action method ? if so, is it valid for individual action method or for the controller?


回答1:


You may use a middleware or override callAction, https://laravel.com/api/5.6/Illuminate/Routing/Controller.html#method_callAction

use Illuminate\Routing\Controller;

class MyController extends Controller
{
    public function callAction($method, $parameters)
    {
        // code that runs before any action
        if (in_array($method, ['method1', 'method2'])) {
            // trigger validation
        }

        return parent::callAction($method, $parameters);
    }
}



回答2:


A built-in solution would be to use middlewares, however I see that you would like to execute that piece of code for specific actions.

If I were you, I'd create a concrete controller class that all my controllers would inherit from, 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();
            }
        }
    }
}

I hope this helps.

Again, the better way would be using middlewares, and to use middlewares for specific actions, you'll need to specify the filtering in the routes, such as :

Route::get('/route_to_my_action', 'MyController@myAction')
->middleware(['my_middleware']);

For further information about this style of filtering in Laravel, visit the docs



来源:https://stackoverflow.com/questions/34261796/before-executing-action-in-laravel-5-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!