Before executing Action in Laravel 5.1


Before executing Action in Laravel 5.1

我正在存储和更新方法中编写以下代码:

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

在执行任何动作方法之前,是否有任何内置的动作方法执行?如果是的话,它对个人行动方法有效还是对控制器有效?

您可以使用中间件或覆盖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);
    }
}

2020更新:

如果您发现自己在Laravel 5+中重复使用验证规则,我建议将它们添加到请求中:https://laravel.com/docs/6.x/validation#form-请求验证

/**
 * Store the incoming blog post.
 *
 * @param  StoreBlogPost  $request
 * @return Response
 */
public function store(StoreBlogPost $request)
{
    // The incoming request is valid...
    // Retrieve the validated input data...
    $validated = $request->validated();
}

一个内置的解决方案是使用中间件,但我看到您希望执行这段代码来执行特定的操作。

如果我是你,我会创建一个具体的controller类,我的所有控制器都将从中继承,这个控制器看起来像这样:

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();
            }
        }
    }
}

我希望这能有所帮助。

同样,更好的方法是使用中间件,要将中间件用于特定操作,您需要指定路由中的过滤,例如:

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

有关Laravel中这种过滤风格的更多信息,请访问文档