php - 在 Laravel 5.1 中执行 Action 之前

标签 php laravel-5 laravel-5.1

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

$v = Validator::make($request->all(), [
    'field' => 'required|max:100|min:5'
]);

if ($v->fails()) {
    return redirect('route name')
                ->withErrors($v)
                ->withInput();
}

是否有在执行任何操作方法之前执行的内置操作方法?如果是这样,它对单个操作方法或 Controller 有效吗?

最佳答案

您可以使用中间件或覆盖callActionhttps://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-request-validation

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

关于php - 在 Laravel 5.1 中执行 Action 之前,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34261796/

相关文章:

apache - 让我们在 Ubuntu 16 apache 服务器上加密 SSL 返回 404 错误

laravel - 如何在 Laravel 5 中按语言环境切换 View ?

php - 允许管理员用户查看其他用户类型可以查看/执行的操作?

php - 每次获取相同值时,Mysql 查询都会运行 COUNT

php - 数据库和 Web 服务器位于不同的提供商机器上

php - 使用正则表达式匹配多个变量(PHP/JS)

php - 将自定义列添加到 laravel excel

datatable - "Class datatables does not exist"使用 "yajra"laravel 数据表时出错

php - IntlDateFormatter 返回错误的年份

laravel - https 请求 "invalid request (unsupported ssl request)"