php 模型中的 Laravel 5 验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37239870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:07:24  来源:igfitidea点击:

Laravel 5 validation in model

phpvalidationlaravellaravel-5laravel-5.2

提问by paranoid

I have model like this

我有这样的模型

class test extends Model
{

public   $rules = [
    'title' => 'required',
    'name' => 'required',
];
protected $fillable = ['title','name'];
}

And controller like this

和这样的控制器

public function store(Request $request)
{
    $test=new test; /// create model object
        $validator = Validator::make($request->all(), [
             $test->rules
        ]);
        if ($validator->fails()) {
            return view('test')->withErrors($validator)
        }
        test::create($request->all());
 }

Validation show error like this

验证显示这样的错误

The 0 field is required.

0 字段是必需的。

I want show this

我想展示这个

The name field is required.
The title field is required.

名称字段是必需的。
标题字段是必需的。

回答by paranoid

I solve it

我解决了

public function store(Request $request)
{
  $test=new test; /// create model object
    $validator = Validator::make($request->all(),$test->rules);
    if ($validator->fails()) {
        return view('test')->withErrors($validator)
    }
    test::create($request->all());
}

回答by Fabian Snaith

You could also look at validating in your model and throwing a ValidationException which will be handled as usual in your controller (with the error bag etc). E.g:

您还可以查看模型中的验证并抛出一个 ValidationException ,该异常将在您的控制器中照常处理(带有错误包等)。例如:

abstract class BaseModel extends Model implements ModelInterface {
    protected $validationRules = [];

    /**
     * Validate model against rules
     * @param array $rules optional array of validation rules. If not passed will validate against object's current values
     * @throws ValidationException if validation fails. Used for displaying errors in view
     */
    public function validate($rules=[]) {
        if (empty($rules))
            $rules = $this->toArray();

        $validator = \Validator::make($rules,$this->validationRules);
        if ($validator->fails())
            throw new ValidationException($validator);
    }

    /**
     * Attempt to validate input, if successful fill this object
     * @param array $inputArray associative array of values for this object to validate against and fill this object
     * @throws ValidationException if validation fails. Used for displaying errors in view
     */
    public function validateAndFill($inputArray) {
        // must validate input before injecting into model
        $this->validate($inputArray);
        $this->fill($inputArray);
    }
}

Then in my Controller:

然后在我的控制器中:

public function store(Request $request) {
    $person = $this->personService->create($request->input());

    return redirect()->route('people.index', $person)->with('status', $person->first_name.' has been saved');
}

Finally in my base service class

最后在我的基本服务类

abstract class BaseResourceService {
    protected $dataService;
    protected $modelClassName;

    /**
     * Create a resource
     * @param array $inputArray of key value pairs of this object to create
     * @returns $object
     */
    public function create($inputArray) {
        try {
            $arr = $inputArray;
            $object = new $this->modelClassName();
            $object->validateAndFill($arr);
            $this->dataService->create($object);
            return $object;
        }
        catch (Exception $exception) {
            $this->handleError($exception);
        }
    }

If the model validates it continues as usual. If there's a validation error it goes back to the previous page with the validation errors in the flash data/error bag.

如果模型验证,它会照常继续。如果出现验证错误,它会返回到上一页,并在闪存数据/错误包中包含验证错误。

I will most probably move the $person->validate() method to my service class, however it will still work as outlined above.

我很可能会将 $person->validate() 方法移到我的服务类中,但它仍然可以按上述方式工作。

回答by codedge

You are doing it the wrong way. The rulesarray should either be in your controller or better in a Form Request.

你这样做是错误的。该rules数组应该在您的控制器中,或者在Form Request 中更好。

Let me show you a better approach:

让我向您展示一个更好的方法:

Create a new Form Requestfile with php artisan make:request TestRequest.

创建一个新的表单请求文件php artisan make:request TestRequest

Example TestRequestclass:

示例TestRequest类:

namespace App\Http\Requests;

use App\Http\Requests\Request;

class TestRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation messages.
     *
     * @return array
     */
    public function messages()
    {
        return [
            'title.required'    => 'A title is required.',
            'name.required'    => 'The name field is required'
        ];
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title' => 'required',
            'name' => 'required',
        ];
    }
}

Inject the requestobject into your controller method.

将请求对象注入您的控制器方法。

public function store(TestRequest $request)
{
    // You don't need any validation, this is already done
    test::create($request->all());
}