English 中文(简体)
模型验证
原标题:Laravel 5 validation in model

我有这样的模式。

class test extends Model
{

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

And Controller喜欢

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());
 }

验证显示的错误就是如此。

需要1个领域。

我想表明这一点。

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

最佳回答

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());
}
问题回答

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

Let me show you a better approach:

www.un.org/Depts/DGACM/index_spanish.htm 创建新的表格文档,php artisan make:request TestRequest

例<代码> 班级:

namespace AppHttpRequests;

use AppHttpRequestsRequest;

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 ,
        ];
    }
}

www.un.org/Depts/DGACM/index_spanish.htm 请求在控制器方法中标。

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

你们还可以看看看你的模式是否正确,并 throw弃一种 Val笑,在你的控制人(有错误的袋子等)将照常处理。 例如:

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);
    }
}

然后,在我的主计长中:

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 );
}

最后,我的基本服务班级

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.

我很可能将“人”和“有效”方法移至我的服务类别,但如上所述,这种方法仍将有效。

你可以简单地以书面形式在模式中验证你。

In your Model File

i.e. Models Test.php

public static $createRules = [
    name => required|max:111 ,
    email => required|email|unique:users ,
];

主计长

public function store(Request $request)
{
     $request->validate(ModalName::$createRules);
     $data = new ModelName();
}

这也是事实。 一切都将是罚款。

解决方案:

use AppHttpRequestsEditRequest; // your handler 

class Link extends Model
{
    private function dublicate(string $class, IlluminateHttpRequest $request)
    {
        $Request = (new $class)->createFromBase($request);
        $validator = IlluminateSupportFacadesValidator::make($Request->validationData(), $Request->rules());
        $Request->setValidator($validator);
        return $Request;
    }
    
    static public function store(Request $request)
    {
            $Request = dublicate(EditRequest::class, $request);     
            $validated = $Request->validated();
    }
}




相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签