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 Create Custom Class or Custom Library in Laravel 11

Create Custom Class or Custom Library in Laravel 11

July 6, 2024July 6, 2024

Custom classes and libraries in Laravel can streamline your application’s codebase by encapsulating common functionality and business logic. This tutorial guides you through creating and utilizing custom classes using Laravel’s powerful features. These classes can be used to encapsulate common functionality, business logic, or to abstract away complex operations. In…

Read More
Javascript Laravel Ajax Autocomplete Using Select2

Laravel Ajax Autocomplete Using Select2

July 17, 2022July 17, 2022

In this article we will learn to use Laravel Ajax Autocomplete Using Select2. Select2 is useful when we want live search of bulk data or to convert the existing select boz with multi features like search, multi select and options customizations. Autocomplete search is mostly work of javascript and when…

Read More
Php How to Import or Convert ExcelCSV to HTML in laravel 8 9

How to Import or Convert Excel/CSV to HTML in laravel 8 / 9?

May 7, 2022May 13, 2022

Excel or CSV are used to store large set of data to analyses and for reporting. In this article we will learn to import excel or CSV in laravel. This tutorial is best fit to you if you want to understand the basic of import in database table with custom…

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

  • 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 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
  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version