如何在laravel中验证多记录插入?

mdfafbf1  于 2023-06-25  发布在  其他
关注(0)|答案(5)|浏览(87)

我的应用程序有一个表单,我在其中插入多条记录,每条记录都是一个新表单。我想验证每个字段在每个形式我试图使用验证功能,但我很困惑如何做多个记录插入?我用的是laravel 5.2。
存储多次插入的函数

public function store(Request $request)
    {
        $this->validate($request,[
            'name' => 'required|min:4',
            'fname' => 'required',
            'rollno' => 'required|unique:students'
        ]);
        $input = $request->all();
        $condition = $input['name'];
        foreach ($condition as $key => $condition) {
            $student = new Student;
            $student->name = $input['name'][$key];
            $student->fname = $input['fname'][$key];
            $student->rollno = $input['rollno'][$key];
            $student->obtainedmarks = $input['obtainedmarks'][$key];
            $student->totalmarks = $input['totalmarks'][$key];
            $student->percentage = $input['percentage'][$key];
            $student->save();
        }
        return Redirect::to('/allresults');

}

用于插入数据的视图

@extends('layouts.app')
@section('content')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

<script type="text/javascript">
    $(function () {
        $('.add').click(function () {
            var n = ($('.resultbody tr').length - 0) + 1;
            var tr = '<tr><td class="no">' + n + '</td>' +
                    '<td><input type="text" class="name form-control" name="name[]" value="{{ old('name') }}"></td>'+
                    '<td><input type="text" class="fname form-control" name="fname[]" value="{{ old('fname') }}"></td>'+
                    '<td><input type="text" class="rollno form-control" name="rollno[]" value="{{ old('rollno') }}"></td>'+
                    '<td><input type="text" class="obtainedmarks form-control" name="obtainedmarks[]" value="{{ old('email') }}"></td>'+
                    '<td><input type="text" class="totalmarks form-control" name="totalmarks[]"></td>'+
                    '<td><input type="text" class="percentage form-control" name="percentage[]"></td>'+
                    '<td><input type="button" class="btn btn-danger delete" value="x"></td></tr>';
            $('.resultbody').append(tr);
        });

        $('.resultbody').delegate('.delete', 'click', function () {
            $(this).parent().parent().remove();
        });

        $('.resultbody').delegate('.obtainedmarks , .totalmarks', 'keyup', function () {
            var tr = $(this).parent().parent();
            var obtainedmarks = tr.find('.obtainedmarks').val() - 0;
            var totalmarks = tr.find('.totalmarks').val() - 0;

            var percentage = (obtainedmarks / totalmarks) * 100;
            tr.find('.percentage').val(percentage);
        });
    });
</script>

<div class="container">
    <div class="row">
        <div class="col-md-10 col-md-offset-1">
            <div class="panel panel-default">
                <div class="panel-heading">Add Results</div>
                @if(count($errors) >0 )
                    <ul>
                        @foreach($errors->all() as $error)
                            <li>{{$error}}</li>
                        @endforeach
                    </ul>
                @endif
                <div class="panel-body">
                   <form class="form-horizontal" role="form" method="POST" action="{{ url('/result') }}">
                        {!! csrf_field() !!}
                    <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Student Name</th>
                                    <th>Father Name</th>
                                    <th>Roll No</th>
                                    <th>Obtained Marks</th>
                                    <th>Total Marks</th>
                                    <th>%</th>
                                    <th>Delete</th>
                                </tr>
                            </thead>
                            <tbody class="resultbody">
                                <tr>
                                    <td class="no">1</td>
                                    <td>
                                        <input type="text" class="name form-control" name="name[]" value="{{ old('name') }}">
                                    </td>
                                    <td>
                                        <input type="text" class="fname form-control" name="fname[]" value="{{ old('fname') }}">
                                    </td>
                                    <td>
                                        <input type="text" class="rollno form-control" name="rollno[]" value="{{ old('rollno') }}">
                                    </td>
                                    <td>
                                        <input type="text" class="obtainedmarks form-control" name="obtainedmarks[]" value="{{ old('email') }}">
                                    </td>
                                    <td>
                                        <input type="text" class="totalmarks form-control" name="totalmarks[]">
                                    </td>
                                    <td>
                                        <input type="text" class="percentage form-control" name="percentage[]">
                                    </td>
                                    <td>
                                        <input type="button" class="btn btn-danger delete" value="x">
                                    </td>
                                </tr>

                            </tbody>
                        </table>    
                        <center><input type="button" class="btn btn-lg btn-primary add" value="Add New Item">   
                        <input type="submit" class="btn btn-lg btn-default" value="Submit"></center>
                        </form>
                </div>
            </div>
        </div>

    </div><!-- First Row End -->
</div> <!-- Container End -->

@endsection

**更新:**在视图中,您会注意到有一个按钮,当用户单击“添加新”时,它会添加新的行行我要验证所有行,每行包含一条记录。

sqyvllje

sqyvllje1#

我认为你可以这样做来验证你的数组输入。

'input_name.*' => 'rules'

https://laravel.com/docs/5.2/validation#validating-arrays
所以在你的情况下:

$this->validate($request,[
     'name.*'   => 'required|min:4',
     'fname.*'  => 'required',
     'rollno.*' => 'required|unique:students'
 ]);
ozxc1zmp

ozxc1zmp2#

Laravel 5.2附带了一系列现成的特性,对于数组验证,您可以查看Validating Arrays
在你的情况下,你应该尝试:

$validator = \Validator::make($request->all(), [
            'name.*' => 'yourRules',
            'fname.*' => 'yourRules',
            'rollno.*' => 'yourRules',
            'obtainedmarks.*' => 'yourRules',
            'totalmarks.*' => 'yourRules'
        ]);

  if($validator->fails()) {
            return back()->withInput()->withErrors($validator->errors());
  }

其他解决方案:

以上解决方案是最完美的,也是最新的一个,特别是针对Laravel 5.2用户。你也可以试试

$validator = \Validator::make($request->all(), [
    'name' => 'array',
    //and your other rules here
]);

之后,使用Validator each方法将定义的规则应用于数组的每个元素。

$validator->each('name','yourRule');
trnvg8h3

trnvg8h33#

表单输入数组使事情变得有点复杂。你在不同的层面上犯了错误:

  • 不考虑行索引位置。
  • 刀片仅渲染一行,而可能有更多行。
  • JavaScript中的刀片语法永远不会起作用。
  • 从不调用验证器。
  • 保存有效记录,而不考虑如果其中一条记录无效,则可能必须返回用户。
  • 选择只返回无效行会增加一些工作,但这是可以做到的。

尝试以下方法作为起点。我没有时间来测试这一切,但它遵循的逻辑,我已经成功地使用了很多次。

视图

@extends('layouts.app')
@section('content')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

<script type="text/javascript">
    $(function () {
        $('.add').click(function () {
            var n = $('.resultbody tr').length - 0;
            var n_adj = n + 1;
            var tr = '<tr><td class="no">' + n_adj + '</td>' +
                    '<td><input type="text" class="name form-control" name="name[n]" value=""></td>'+
                    '<td><input type="text" class="fname form-control" name="fname[n]" value=""></td>'+
                    '<td><input type="text" class="rollno form-control" name="rollno[n]" value=""></td>'+
                    '<td><input type="text" class="obtainedmarks form-control" name="obtainedmarks[n]" value=""></td>'+
                    '<td><input type="text" class="totalmarks form-control" name="totalmarks[n]"></td>'+
                    '<td><input type="text" class="percentage form-control" name="percentage[n]"></td>'+
                    '<td><input type="button" class="btn btn-danger delete" value="x"></td></tr>';
            $('.resultbody').append(tr);
        });

        $('.resultbody').delegate('.delete', 'click', function () {
            $(this).parent().parent().remove();
        });

        $('.resultbody').delegate('.obtainedmarks , .totalmarks', 'keyup', function () {
            var tr = $(this).parent().parent();
            var obtainedmarks = tr.find('.obtainedmarks').val() - 0;
            var totalmarks = tr.find('.totalmarks').val() - 0;

            var percentage = (obtainedmarks / totalmarks) * 100;
            tr.find('.percentage').val(percentage);
        });
    });
</script>

<div class="container">
    <div class="row">
        <div class="col-md-10 col-md-offset-1">
            <div class="panel panel-default">
                <div class="panel-heading">Add Results</div>
                @if(count($errors) >0 )
                    <ul>
                        @foreach($errors->all() as $error)
                            <li>{{$error}}</li>
                        @endforeach
                    </ul>
                @endif
                <div class="panel-body">
                   <form class="form-horizontal" role="form" method="POST" action="{{ url('/result') }}">
                        {!! csrf_field() !!}
                    <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Student Name</th>
                                    <th>Father Name</th>
                                    <th>Roll No</th>
                                    <th>Obtained Marks</th>
                                    <th>Total Marks</th>
                                    <th>%</th>
                                    <th>Delete</th>
                                </tr>
                            </thead>
                            <tbody class="resultbody">

                                @for ($i = 0; $i < isset($row_count) ? $row_count : 1; $i++)
                                <tr>
                                    <td class="no">{{ $i+1 }}</td>
                                    <td>
                                        <input type="text" class="name form-control" name="name[]" value="{{ old('name['.$i.']', null) }}">
                                    </td>
                                    <td>
                                        <input type="text" class="fname form-control" name="fname[]" value="{{ old('fname['.$i.']', null) }}">
                                    </td>
                                    <td>
                                        <input type="text" class="rollno form-control" name="rollno[]" value="{{ old('rollno['.$i.']', null) }}">
                                    </td>
                                    <td>
                                        <input type="text" class="obtainedmarks form-control" name="obtainedmarks[]" value="{{ old('obtainedmarks['.$i.']', null) }}">
                                    </td>
                                    <td>
                                        <input type="text" class="totalmarks form-control" name="totalmarks[]" value="{{ old('totalmarks['.$i.']', null) }}">
                                    </td>
                                    <td>
                                        <input type="text" class="percentage form-control" name="percentage[]" value="{{ old('percentage['.$i.']', null) }}">
                                    </td>
                                    <td>
                                        <input type="button" class="btn btn-danger delete" value="x">
                                    </td>
                                </tr>
                                @endfor

                            </tbody>
                        </table>    
                        <center><input type="button" class="btn btn-lg btn-primary add" value="Add New Item">   
                        <input type="submit" class="btn btn-lg btn-default" value="Submit"></center>
                        </form>
                </div>
            </div>
        </div>

    </div><!-- First Row End -->
</div> <!-- Container End -->

@endsection

store()

use Validator;

// ...

public function store(Request $request)
    {

        $validation_rules = [
            'name' => 'required|min:4',
            'fname' => 'required',
            'rollno' => 'required|unique:students'
        ];

        $validation_messages = [
            // add custom error messages
        ];

        $name = $request->input('name');
        $fname = $request->input('fname');
        $rollno = $request->input('rollno');
        $obtainedmarks = $request->input('obtainedmarks');
        $totalmarks = $request->input('totalmarks');
        $percentage = $request->input('percentage');

        // number of rows submitted (use a required value)
        $n = count($names);

        // track valid student records
        $students = [];

        for ($i=0; $i < $n; $i++) {
            $data = [
                'name' => $name[$i],
                'fname' => $fname[$i],
                'rollno' => $rollno[$i],
                'obtainedmarks' => $obtainedmarks[$i],
                'totalmarks' => $totalmarks[$i],
                'percentage' => $percentage[$i]
            ];
            $validator = Validator::make($data, $validation_rules, $validation_messages);

            if ($validator->fails()) {
                // redirect back to form
                return redirect()->back()->withInput($request->all())->with('errors', '$validator->errors());
            }

            $students[] = $data;
        }

        foreach ($students as $row) {
            Student::create($row);
        }

        return redirect('/allresults');

}
8gsdolmq

8gsdolmq4#

$failed = false;
$errors = [];
        foreach($data['name'] as $key => $val){

            $v = Validator::make($val, [
                        'name' => 'unique:users'
             ]);


             if ($validator->fails()) {
                $failed = true;
                 $error = [
                     'msg' => $v->errors()->all(),
                     'number' => $val['name'],
                 ];
                 array_push($errors, $error); 
             }

        }

if($failed == true){
    return['msg' => false, 'data' => $errors];
}

试试这个:)

wz8daaqr

wz8daaqr5#

对于多记录验证,使用记录号自定义消息

<?php

namespace App\Http\Requests\Modules\Export\ExportBooking;

use App\Rules\PhoneRule;
use App\Traits\ApiResponser;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;

class ExportBookingCreateRequest extends FormRequest
{
    use ApiResponser;

    public function rules()
    {
        $rules = [
            'booking_date' => 'required|date',
            'exp_organization_id' => ['required','integer', Rule::exists('organization', 'id')->where('is_export', 1) ],
            'marketing_person_id' => 'required|integer|exists:marketing_person,id',
            'customer_id' => 'required|integer|exists:customer,id',

            'exp_booking_dtl' => 'required',
        ];

        $exp_booking_dtl = $this->input('exp_booking_dtl');

        foreach ($exp_booking_dtl as $rowNumber => $item) {
            $rules["exp_booking_dtl.{$rowNumber}.product_id"] = "required|integer|exists:product,id";
            $rules["exp_booking_dtl.{$rowNumber}.product_sticker_id"] = "required|integer|exists:product_sticker,id";
            $rules["exp_booking_dtl.{$rowNumber}.po_number_id"] = "nullable|integer|exists:po_number,id";
            $rules["exp_booking_dtl.{$rowNumber}.qty"] = "required|numeric|gt:0";
        }
        return $rules;
    }
    public function messages()
    {
        $messages = [];
        $exp_booking_dtl = $this->input('exp_booking_dtl');

        foreach ($exp_booking_dtl as $rowNumber => $item) {

            $messages["exp_booking_dtl.{$rowNumber}.product_id.required"] = "Booking Detail Rec-".($rowNumber+1).": Product is required.";
            $messages["exp_booking_dtl.{$rowNumber}.product_id.exists"] = "Booking Detail Rec-".($rowNumber+1).": Invalid Product.";

            $messages["exp_booking_dtl.{$rowNumber}.product_sticker_id.required"] = "Booking Detail Rec-".($rowNumber+1).": Product Sticker is required.";
            $messages["exp_booking_dtl.{$rowNumber}.product_sticker_id.exists"] = "Booking Detail Rec-".($rowNumber+1).": Invalid Product Sticker.";

            $messages["exp_booking_dtl.{$rowNumber}.po_number_id.exists"] = "Booking Detail Rec-".($rowNumber+1).": Invalid PO Number.";

            $messages["exp_booking_dtl.{$rowNumber}.qty.required"] = "Booking Detail Rec-".($rowNumber+1).": Qty is required.";
            $messages["exp_booking_dtl.{$rowNumber}.qty.gt"] = "Booking Detail Rec-".($rowNumber+1).": Qty must be greater than :value.";
        }
        return $messages;
    }
    public function failedValidation(Validator $validator)
    {
        throw new HttpResponseException(
            $this->set_response(null, 422, 'error', $validator->errors()->all(), new Request($this->request->all()))
        );
    }
}

相关问题