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 How to Change Date Format in Json Response Laravel

How to Change Date Format in Json Response Laravel ?

July 9, 2022November 17, 2023

In json response we get different data format and to change date format in Json Response Laravel we need to make bit extra efforts to show correct date format. Laravel provides by default two timestamp created_at and updated_at, and there format are according to database format but sometimes we want…

Read More
Php How to Implement JWT Auth in Laravel

How to Implement JWT Auth in Laravel 9 ?

May 31, 2022August 20, 2022

JWT (Json Web Token) is used to create the authentication between two parties client and server that means it creates a secure information transactions between two parties. In the process of php-open-source-saver/jwt-auth token it creates a token claims and generates a token behalf of these claims then it verify on…

Read More
Php How to Upload image with preview in Laravel 8 with example

How to Upload image with preview in Laravel 8 with example ?

May 14, 2022August 20, 2022

Upload image with preview in laravel or for any website can be basic requirement like set up a profile picture to providing the documents. Laravel provides robust functionality to upload and process the image with security. Laravel simply use Request file method to access the uploaded file and then we…

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

  • 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

  • Mastering Schedule Management with Laravel Zap
  • The Resilience of Nature: How Forests Recover After Fires
  • Understanding Laravel Cookie Consent for GDPR Compliance
  • Understanding High Vulnerabilities: A Critical Overview of the Week of May 12, 2025
  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version