Мое приложение имеет форму, в которую я вставляю несколько записей, каждая запись представляет собой новую форму. Я хочу проверить каждое поле в каждой форме, я пытался использовать функцию проверки, но я смущен, как это сделать для ввода нескольких записей? Для этого проекта я использую 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
в@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
Обновление: в представлении вы заметите, что есть кнопка, когда пользователь нажимает «добавить новый», он добавляет новую строку строки. Я хочу проверить все строки, каждая строка содержит запись.
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');
Я думаю, вы можете сделать это, чтобы подтвердить свой ввод массива.
'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' ]);
Массивы ввода формы делают вещи немного более сложными. Вы делаете ошибки на разных уровнях:
Попробуйте следующее в качестве начальной точки. У меня не было времени проверить все это сейчас, но оно следует логике, которую я успешно использовал много раз.
@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
в@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
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'); }
$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]; }
Попробуй это 🙂