【问题标题】:validate and saving an array of objects laravel 6, vue, axios验证并保存一组对象 laravel 6、vue、axios
【发布时间】:2020-08-08 15:27:36
【问题描述】:

vue函数:

        sendData() {
        this.isLoading = true;
        const postData = {
            data: this.items,

        };
        var self = this;
        axios.post(this.postUrl, postData).then(function (response) {
            console.log(response.data);

           self.isLoading = false;
        });

        this.items = [];
    },

Laravel 控制器:

    public function store(request $request)
{

    foreach ($request->data as $data) {

        $serie = [];

        $serie = ['imei' => $data['serie']];

        $imei = new Imei([
            'imei' => $data['serie'],
            'status_id' => 1,
            'sucursal_id' => $data['sucursal'],
            'equipo_id' => $data['equipo']

        ]);

        $validator = Validator::make($serie, [
            'imei' => 'unique:imeis,imei|digits:15',



        ]);
        if ($validator->fails()) {

// Here I need to build the response of every imei with its validation error

        } else {

            $imei->save();


        }


    }


    return >Here I want to return the errors back to vue 
}

我的 vue 应用程序通过 axios 向 laravel 发送一个看起来像这样的对象数组 [{imei:xxxx,sucursal_id...},{imei:xxxx,sucursal_id...}] 我需要验证 imei 是唯一的并且保存它,如果错误以相同的方式返回错误 [{imei:xxxx,errorMsg: 'already exists in DB'}]。但我找不到正确的方法。

【问题讨论】:

    标签: php json laravel vue.js axios


    【解决方案1】:

    基本上你想自定义你的 errorbag​​ 对吗?试试这个。将此添加到您的失败条件中。让我知道它是否有效。

    $err = [{imei:xxxx,errorMsg: 'already exist in DB'}]; 
    
    foreach ($validator->errors()->toArray() as $error)  {
        foreach($error as $sub_error) {
               array_push($err, $sub_error);
            }
      }
    return ['errors'=>$err];
    
    

    【讨论】:

      猜你喜欢
      • 2023-03-16
      • 2018-05-06
      • 1970-01-01
      • 2017-12-16
      • 2019-08-03
      • 2021-05-22
      • 2018-02-23
      • 2020-05-05
      • 2019-02-08
      相关资源
      最近更新 更多