gpt4 book ai didi

php - 在 laravel 中具有跨多个 Controller 的通用验证功能

转载 作者:行者123 更新时间:2023-12-05 07:47:44 25 4
gpt4 key购买 nike

尝试学习 laravel。

我有一个发布到这条路线的用户表单

Route::post('users/add','usersController@store')->middleware('admin');

usersController 中的存储函数调用另一个名为 validateForm 的函数,它基本上验证来自表单的输入,就像这样

class usersController extends Controller
{
/*
*Store a user in database
*/
function store(){
$input=Request::all();

// create the validation rules ------------------------
$rules = array(
'name' => 'required', // just a normal required validation
'lastname' => 'required', // just a normal required validation
'email' => 'required|email|unique:users', // required and must be unique in the users table
'password' => 'required',

);
$validationResponse=$this->validateForm($input,$rules);

if($validationResponse=="passed"){


$user=new \App\User;
$user->name=$input['name'];
$user->email=$input['email'];
$user->lastname=$input['lastname'];
$user->password=\Hash::make($input['password']);
$user->userlevel=isset($input['isAdmin'])?1:0;
$user->save();

return redirect('users');
}
else{
return Redirect::to('users/create')
->withErrors($validationResponse)->withInput();


}


}

/*
*validate user form input
*/
function validateForm($input,$rules){

// do the validation ----------------------------------
// validate against the inputs from our form
$validator = Validator::make($input, $rules);

// check if the validator failed -----------------------
if ($validator->fails()) {

// get the error messages from the validator
$messages = $validator->messages();

return $messages;
}
else{
return 'passed';
}
}
}

现在这对于从 userController 访问没问题,但是如果我有另一个 Controller 说 projectsController 并且我想访问相同的功能,即 validateForm

我应该把这个通用函数放在哪里,我如何从任何 Controller 访问它?

最佳答案

Laravel 内置对此的回答是 Form Request

只需使用 php artisan make:request UserCheck 创建一个表单请求,并将您的验证规则放入方法 rules

/**
* Get the validation rules that apply to the request.
*
* @return array
*/

public function rules() {
return [
'name' => 'required', // just a normal required validation
'lastname' => 'required', // just a normal required validation
'email' => 'required|email|unique:users', // required and must be unique in the users table
'password' => 'required',

]; }

然后调用它

/*
* Store a user in database
*/
public function store(UserCheck $request)
{
// The incoming request is valid...
}

关于php - 在 laravel 中具有跨多个 Controller 的通用验证功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39339713/

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