简体   繁体   中英

Data validation in the model

I'm not new to Laravel, but I'm probably making an architectural mistake somewhere.

I have a class (second layer above the model) where all the business logic is stored. I need to validate incoming data, for example: to be email, to be in email format, to be unique, and so on. A validator is great for this.

I COULD do this in the controller: $request-validate() . But I want to validate in the model itself because the method can be called from different places like UserController and GraphQL::createUserMutation .

Writing the same code in two places is a bad idea, isn't it?

In UserController:

$validator = Validator::make(
  $request->all(),
  [
    'email' => 'email|max:255|unique:users',
    'password' => 'required|min:6|max:20|confirmed',
    'password_confirmation' => 'required|same:password',
  ],
);
    
if ($validator->fails()) {
 ...
}

User::query()->createUser($request->all());

And GraphQL createUserMutation:

$validator = Validator::make(
  $request->all(),
  [
    'email' => 'email|max:255|unique:users',
    'password' => 'required|min:6|max:20|confirmed',
    'password_confirmation' => 'required|same:password',
  ],
);
    
if ($validator->fails()) {
 ...
}

User::query()->createUser($request->all());

Therefore, I prefer to check in one place: in the model.

Everything works successfully if I return an array:

if ($validator->fails()) {
   return $validator->messages();
}

But what if I want to throw an Exception? I translate the error message to a string and throw an Exception:

$result = [];
foreach ($messages->toArray() as $field => $messagesList) {
  foreach ($messagesList as $msg){
   $result[] = '- '.$msg;
  }
}
throw new \Exception(implode("\n<br/>", $result));

How correct is my approach? Perhaps I am reinventing the wheel, but so far I have not found a better solution. Or, still stick to the validation in the controller, duplicating the validation code?

I think you are missing Form Request Validation in Laravel

Step One: Create a request by artisan command php artisan make:request YourRequestName

This will create a class named YourRequestName.php in directory app\Http\Requests

Step Two: Open this file you will find by default a rule function in which you will just return an array of your rules

Step Three: Add a function called messages in which you will return an array of validation messsages

Step Four: In any method in your project you want to use YourRequestName to make validation just inject it as a parameter instead of Request Class

An example of a request class StoreRequest : 一个请求类 StoreRequest 的例子

And in controller you will inject it like that: 在此处输入图像描述

And don't forget to use StoreRequest Class in your controller

And Finally this is the section in laravel documentation:

https://laravel.com/docs/9.x/validation#form-request-validation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM