Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks

Laravel array validation with example

Aman Jain, December 15, 2021November 12, 2023

In this tutorial i will explain to use validating a array inputs using Laravel validation library. Laravel also supports to validate group of array and we can validate a array same as normal input. In our recent article Laravel form validation how to validate a form and files.

In this post i will show you to validate a array in form or in a http request. To implement the Laravel array validation we will use a form with array and then we will validate in Laravel controller.

To validate a array in Laravel we can use

<h3>Laravel array form validation  - Readerstacks</h3>
            @if ($errors->any())
                <div class="alert alert-danger">
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif
            <form method="post"   action="{{url('articles/save')}}" name="postform">
              <div class="form-group">
                <label>Email</label>
                <input type="email" name="email"  value="" class="form-control" />
                 @csrf
              </div>

              <div class="form-group">
                <label>Names 1</label>
                <input type="text" name="names[]"  value="{{old('names[0]')}}" class="form-control" />
                @error('names.0')
                    <div class="alert alert-danger">{{ $message }}</div>
                @enderror
                
              </div>
              <div class="form-group">
                <label>Names 2</label>
                <input type="text" name="names[]"  value="{{old('names[1]')}}" class="form-control" />
                @error('names.1')
                    <div class="alert alert-danger">{{ $message }}</div>
                @enderror
              </div>
               
              <div class="form-group">
                <button type="submit" class="btn btn-primary">Submit</button>
              </div>
            </form>

Here we are showing the error message below the input and also above the form just for example and in controller

 $validator = Validator::make($request->all(), [
            'names.*' => ['required']   // required and email format validation
        ],[
            // "names.*.required"=>"Name field is required "
        ]); // create the validations

here * is used for array and we can also customize the error message as you can see .

Example 2 for multidimentional array validation laravel

Sometimes we wanted to validate multidimentional array validation laravel so here is the example of multidimentional array

[0] => Array
    (
        [item_id] => 1
        [title] => "aaa"
        [size] => "L"
    )
[1] => Array
    (
        [item_id] => 2
        [title] => "BBB"
        [size] => "XL"
    )

So to validate this we need below syntax

$this->validate($request, [
    '*.item_id' => 'required|integer',
    '*.title' => 'required',
    '*.size'    => 'required|max:191',
]);

Let’s understand the Laravel array validation with example

Step 1 : Create a controller

Create the controller and add the necessary imports and class. You can create by Laravel artisan or manually.

php artisan make:controller ArticleController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Article;
use Illuminate\Support\Facades\Validator;



class ArticleController extends Controller
{

    

    public function form(Request $request, $id = 0)
    {
        return view("articles.form");
    }

    public function store(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'names.*' => ['required']   // required and email format validation

        ], [
            // "names.*.required"=>"Name field is required "
        ]); // create the validations
        if ($validator->fails())   //check all validations are fine, if not then redirect and show error messages
        {

            return back()->withInput()->withErrors($validator);
            // validation failed redirect back to form

        } else {
            //handle the form 
        }
    }
}

Here, we have created two methods one for show the form and another one for validating the form. As you can see we. have used * to validate the array.

Step 2: Create blade file for view

Now it’s time to show the form and validation message to our view, so let’s create the view file.

<h3>Laravel array validation - Readerstacks</h3>
            @if ($errors->any())
                <div class="alert alert-danger">
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif
            <form method="post" id="handleAjax" action="{{url('articles/save')}}" name="postform">
              <div class="form-group">
                <label>Email</label>
                <input type="email" name="email"  value="" class="form-control" />
               
                 @csrf
              </div>

              <div class="form-group">
                <label>Names 1</label>
                <input type="text" name="names[]"  value="{{old('names.0')}}" class="form-control" />
                @error('names.0')
                    <div class="alert alert-danger">{{ $message }}</div>
                @enderror
                
              </div>
              <div class="form-group">
                <label>Names 2</label>
                <input type="text" name="names[]"  value="{{old('names.1')}}" class="form-control" />
                @error('names.1')
                    <div class="alert alert-danger">{{ $message }}</div>
                @enderror
                
              </div>
               
              <div class="form-group">
                <button type="submit" class="btn btn-primary">Submit</button>
              </div>
            </form>

In above code we have created name fields which can be multiple and also showing the error message above the form and also below the input just for example.

Step 3: Create routes

Now, open the routes/web.php and add below routes

<?php

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

Route::get('/articles',[ArticleController::class, 'index']); 
Route::post('/articles/save',[ArticleController::class, 'store']); 

Now run php artisan serve command and check the implementation in browser.

Here is the screenshot

Laravel Array Validation
Laravel Array Validation
Laravel Array Validation
Laravel Array Validation
Laravel array validation

Customizing error message of validation

TO customize the validation message we need to pass second parameter to Validator::make() method as below

 $validator = Validator::make($request->all(), [
            'names.*' => ['required']   // required and email format validation

        ], [
            "names.*.required"=>"Name field is required "
        ]); 

We can also change message for each array field as below

  $validator = Validator::make($request->all(), [
            'names.*' => ['required']   // required and email format validation

        ], [
            "names.0.required"=>"Name 1 field is required ",
            "names.1.required"=>"Name 2 field is required "
        ]);
Screenshot 2021 12 15 at 8.45.55 AM
Customizing error message

Related

Php Laravel arraylaravelvalidation

Post navigation

Previous post
Next post

Related Posts

Php Laravel 9 Ajax CRUD with Search, Image and Pagination

Laravel 9 Ajax CRUD with Search, Image and Pagination

June 26, 2022March 28, 2023

In this article i will learn Ajax CRUD with Search, Image and Pagination in laravel 9. When we want to perform the CRUD operations without reloading the page then we use javascript and Ajax to refresh the page content without reloading.In this post we will not only cover the Ajax…

Read More
Php How to create custom logs file in laravel 8 9

How to create custom logs file in laravel 8 / 9 ?

May 16, 2022May 16, 2022

In this article i will show you to use and create custom logs file in laravel. Logging is an important aspect when you want to debug your application or you want to monitor the user activities on the application. Laravel itself provides a robust library to create logging on daily…

Read More
Php Custom helper function laravel

How to Create Custom Helper Functions in Laravel ?

December 21, 2021November 8, 2023

Sometimes in our application we want to create custom helper functions in laravel to use in our application, Laravel has so many helpers functions to work with strings, URL, email, array, debugging etc. so in this article i will show you to use custom helper functions in our Laravel application….

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • August 2025
  • July 2025
  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • The Transformative Power of Education in the Digital Age
  • Understanding High Vulnerabilities: A Closer Look at the Week of July 14, 2025
  • Exploring Fresh Resources for Web Designers and Developers
  • The Intersection of Security and Technology: Understanding Vulnerabilities
  • Mapping Together: The Vibrant Spirit of OpenStreetMap Japan
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version