使用观察者请求验证 [英] Request Validation using Observers

查看:87
本文介绍了使用观察者请求验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

借助观察者,我将其他内容添加到模型/数据库中. 这没有问题!!

With an observer, I add additional content to the model / database. This works without problems!!

现在,我想验证传入的请求,但是不幸的是,我不知道如何在观察者中插入验证或规则.

Now I would like to validate the incoming request, but unfortunately I do not know how to insert a validation or rules in the observer.

class Customer
{
    /**
     * @var array
     */
    protected $rules = [
        'firstname' => 'numeric',
        'name1' => 'string',
        //'client_number' => 'required|string|unique:customers',
    ];

    /**
     * Listen to the updated event.
     *
     * @param Model $customer
     * @return void
     */
    public function saving(Model $customer)
    {    
        if (request('firstname'))
        {
            if (request('firstname') != null)
            {
                $customer->firstname = request('firstname');
            }
            else
            {
                $customer->firstname = NULL;
            }            
        }

        $customer->client_number = '123456789';
    }
}

推荐答案

首先,我认为您应该避免使用Model Observer进行请求验证. laravel为此提供了其他功能,例如表单请求验证.

First of all I think you should avoid to use a Model Observer for request validation. There are other features that laravel provides for this, like the Form request validation.

另一方面,您可以手动创建验证器.这是一个遵循您问题代码的示例:

On the other side, you can manually create a validator that runs inside your observer (or any other part of your code). Here an example that follows your question's code:

class Customer
{
    /**
     * @var array
     */
    protected $rules = [
        'firstname' => 'numeric',
        'name1' => 'string',
        //'client_number' => 'required|string|unique:customers',
    ];

    /**
     * Listen to the updated event.
     *
     * @param Model $customer
     * @return void
     */
    public function saving(Model $customer)
    {    
        $validator = Validator::make(request()->all(), $this->rules);

        if ($validator->fails()) {
            // Fail logic
        } else {
            // Success logic
        }
    }
}

这篇关于使用观察者请求验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆