gpt4 book ai didi

php - 在 Laravel 5.1 中执行 Action 之前

转载 作者:可可西里 更新时间:2023-11-01 12:55:19 25 4
gpt4 key购买 nike

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

$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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com