Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

array validation in laravel 8

How to validate array values in Laravel?

Today, I will give you an example of “How to validate array values in Laravel”, So you can easily apply it with your laravel 5, laravel 6, laravel 7, laravel 8, and Laravel 9 application.

First, what we’re doing here, This is the example :

add more text box in laravel

add and remove text fields in laravel using jQuery

multiple array validation in laravel

Multiple array validation in Laravel

We have a lot of opportunities to validate the incoming data of the application in laravel. Validates requests trait is used by default in Laravel with the help of its base controller to process the validation.

We validate requests using two ways which are convenient as it is an easier way to validate any incoming HTTP requests. It also holds a good variety of powerful and useful rules of validation.

The two ways of validation in Laravel are:

  1. Inside the controller action
  2. With the help of a dedicated form request.

Related article:- The Smart Way To Handle Request Validation In Laravel.

Array validation in Laravel 8 Example :

Add/remove multiple input fields dynamically with Jquery Laravel-:

We will create a form using jQuery, The jQuery method will help to insert and remove content at the end of the selected HTML elements.

We will get all the form request parameter values of the array and validate them on the controller.

routes\web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\BookController;


Route::get('/add-book', [BookController::class, 'addBook']);
Route::post('/book-store', [BookController::class, 'storeBook'])->name('book.store');

app\Http\Controllers\BookController.php :

<?php

namespace App\Http\Controllers;
use Session;
use App\Models\Book;
use Illuminate\Http\Request;

class BookController extends Controller
{

    public function addBook(){
        return view('booksExample.create');
    }

    public function storeBook(Request $request)
    {
        #validate request with custom messages
        $request->validate([
            'book_name.*'   => 'required',
            'book_author.*' => 'required',
            'book_price.*'  => 'required'     
        ], 
        ['book_name.*.required'  => 'Book name field can not be empty value.', 
         'book_author.*.required'=> 'Book author field can not be empty value.',
         'book_price.*.required' => 'Book price field can not be empty value.',]);
    }
}

resources\views\booksExample\create.blade.php :

add more functionality using jQuery in laravel
<!DOCTYPE html>
<html>
   <head>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
      <style>
      form .error {
      color: #ff0000;
    }
</style>
   </head>
   <body>
      <br><br>
      <div class="container">
      <div class="row justify-content-center">
         <form action="{{route('book.store')}}" method="POST">
            @csrf
            <div class="wraps">
               <div class="row">
                  <div class="form-group col-md-3">
                     <label for="">Enter Book Name</label>
                     <input type="text" class="form-control"  name="book_name[0]" placeholder="Please enter book name">
                      <span class="errormsg text-danger">{{ $errors->first('book_name.*') }} </span>
                  </div> 
                 <div class="form-group col-md-3">
                     <label for="">Book Author</label>
                     <input type="text" class="form-control" name="book_author[0]" placeholder="Please enter book author">
                    <span class="errormsg text-danger">{{ $errors->first('book_author.*') }} </span>
                  </div>
                  <div class="form-group col-md-3">
                     <label for="">Book Price</label>
                     <input type="text" class="form-control" name="book_price[0]" placeholder="Please enter book price">
                    <span class="errormsg text-danger">{{ $errors->first('book_price.*') }} </span>
                  </div>
                 <br>
                  <button type="button" class="btn btn-success btn-md" id="add_more"></i>Add More</button>
               </div>
            </div>
      </div>
      <button type="submit" class="btn btn-info">Submit</button>
      <input type="hidden" id="count1" value="0" name="">
      </form>
   </body>
</html>
<script type="text/javascript">
   $(document).ready(function(){
   $('#add_more').click(function(){
   
   var count=$('#count1').val();
   var count_new=parseInt(count)+1;
   var add_section='<div class="wraps"'+count_new+'"><div class="row">  <div class="form-group col-md-3"> <input type="text" class="form-control" placeholder="Please enter book name" name="book_name['+count_new+']"><span class="errormsg text-danger">{{ $errors->first('book_name.*') }} </span></div><div class="form-group col-md-3"> <input type="text" class="form-control" placeholder="Please enter book author" name="book_author['+count_new+']"><span class="errormsg text-danger">{{ $errors->first('book_author.*') }} </span></div><div class="form-group col-md-3"> <input type="text" class="form-control" placeholder="Please enter book price" name="book_price['+count_new+']"><span class="errormsg text-danger">{{ $errors->first('book_price.*') }} </span></div><button class="btn btn-danger btn-md remove_books remove">Remove</button></div>';
   $('.wraps:last').after(add_section);
   var count=$('#count1').val(count_new);
   });
   $(document).on('click','.remove_books', function(){
   var removeCount = $("#count2").val();
   var removeCount2 = parseInt(removeCount)-1;
   $(this).parent().parent().remove();
   var i=1;
   $("[id^='addmore_book_']").each(function(){
   var new_id= 'addmore_book_'+i;
   $(this).attr('id',new_id);
   i= i+1;
   });
   $("#count1").val(removeCount2);
   });
});
</script>
</body>
</html>

Run application :

http://127.0.0.1:8000/add-product
array validation in laravel 8

add and remove text fields in laravel

laravel validate Array

In this article, we learned “How to validate array values in Laravel”, I hope this article will help you with your Laravel application Project.

Also Read:- Laravel 8 database notification example.