Web Engineer Web Engineer - 5 months ago 49
PHP Question

How to validate multiple records insertion in laravel?

My app has a form where I insert multiple records, each record is a new form. I want to validate each field in each form I tried to use validate function but I am confused how to do it for multiple records insert ? For this project I am using laravel 5.2.

Store Function For Multiple Insert

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

}


View For Inserting data

@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


Update : In the view you will notice there is a button when the user click on that "add new" it adds new row row I want to validate all the rows, each row contains a record.
enter image description here

Answer

Laravel 5.2 comes with bundle of ready features, for array validations you can take a look on Validating Arrays

In your case you should try :

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

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

Another Solution:

The above solution is perfect and latest one, specially for Laravel 5.2 users. You can also try

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

After that use Validator each method to apply your defined rules to each element of the array.

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