gpt4 book ai didi

php - 如何在 Laravel 中合并两个请求

转载 作者:行者123 更新时间:2023-12-02 03:00:24 26 4
gpt4 key购买 nike

在我的 Laravel (5.1) 项目中,我需要创建一个验证表单的请求。

但是对于这个请求,我想合并两个不同的请求:

第一个请求:

class AdvertisementRequest extends Request {

public function authorize()
{

return true;
}

public function rules()
{
return [
'ads_type' => 'required|numeric|in:0,1',
'category' => 'required|numeric|exists:categories,id',
'title' => 'required|alpha_num|max:45',
'description' => 'required|alpha_num|max:2000',
'price' => 'required|numeric',
];
}

}

第二个请求:

class UserRegisterRequest extends Request {

public function authorize()
{

return true;
}

public function rules()
{
$rules = [
'form_type' => 'required|numeric|in:0,1',
'user_type' => 'required|numeric|in:0,1',
'phone' => 'required|phone_number',
'region' => 'required|numeric|exists:regions,id',
'department' => 'required|numeric|exists:departments,code',
'postal_code' => 'required|postal_code',
'city' => 'alpha|max:45',
'id_city' => 'required|numeric|exists:cities,id',
'last_name' => 'required|alpha_sp|max:45',
'first_name' => 'required|alpha_sp|max:45',
'pseudo' => 'required|alpha|max:45|unique:users',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|alpha_num|min:6|max:45',
];

return $rules;
}
}

我想创建第三个请求,将其他两个请求结合起来:

class UserAdvertisementRegisterRequest extends Request {

public function authorize()
{

return true;
}

public function rules()
{
$rules = [
'ads_type' => 'required|numeric|in:0,1',
'category' => 'required|numeric|exists:categories,id',
'title' => 'required|alpha_num|max:45',
'description' => 'required|alpha_num|max:2000',
'price' => 'required|numeric',

'form_type' => 'required|numeric|in:0,1',
'user_type' => 'required|numeric|in:0,1',
'phone' => 'required|phone_number',
'region' => 'required|numeric|exists:regions,id',
'department' => 'required|numeric|exists:departments,code',
'postal_code' => 'required|postal_code',
'city' => 'alpha|max:45',
'id_city' => 'required|numeric|exists:cities,id',
'last_name' => 'required|alpha_sp|max:45',
'first_name' => 'required|alpha_sp|max:45',
'pseudo' => 'required|alpha|max:45|unique:users',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|alpha_num|min:6|max:45',
];

return $rules;
}
}

是否有任何解决方案可以在不重复我的代码的情况下做到这一点?

抱歉我的英语不好:/.

先谢谢您的回复!

最佳答案

最简单的方法是通过以下方式在 UserAdvertisementRegisterRequest::rules 方法中生成验证规则的合并列表:

class UserAdvertisementRegisterRequest extends Request { 
public function rules()
{
return array_merge(
with(new AdvertisementRequest)->rules(),
with(new UserRegisterRequest)->rules()
);
}
}

关于php - 如何在 Laravel 中合并两个请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34256263/

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