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 Show Success and Error Flash Message in Laravel

How to Show Success and Error Flash Message in Laravel 10 ?

March 26, 2023March 16, 2024

This article aims to teach how to display flash messages indicating success or error in Laravel 10. Flash messages come in handy when notifying users of recent activities such as form submissions or website actions. In such cases, multiple types of messages may be required. Sometimes, error messages need to…

Read More
Php Laravel 11 Ajax Image Upload with form with example

Laravel 11 Ajax Image Upload with form with example

July 16, 2024July 16, 2024

In this tutorial, I will demonstrate how to implement Laravel 11 Ajax Image Upload with form. This can be achieved using Laravel’s file and storage providers. In our previous articles, such as How to Upload image in Laravel 11 ? we explained how to upload images without Ajax. However, today…

Read More
Php How to Change Date Format in Laravel

How to Change Date Format in Laravel ?

July 6, 2022November 17, 2023

In this blog we will learn to change date format in laravel. Laravel provides by default two timestamp created_at and updated_at, and there format are according to database format but sometimes we want to show different format across the entire application so In this tutorial we will learn to change…

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

  • Building a Million-Dollar Brand: The Journey of Justin Jackson
  • 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
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version