Laravel Validator for Array Length

 

In this blog post, We are going to learn about validation rules for Array length. This is useful for some of the programs which are very specific to data. 


Sometimes, we require this validation in our Laravel projects to calculate the array length with validator rules. We will be using array, min, max, between, and size for validator rules.


Let's start with code and examples,


Laravel Validation for Array Min:


When you have to validate that an array contains at least three users, you can apply the min rule:


'users' => 'array|min:3'


Laravel Validation for Array Max:


When you have to validate that an array contains more than three users, you can apply the max rule:


'users' => 'array|max:3'



Laravel Validation for Array Between:


When you have to validate that an array contains at least three, but not more than ten users, you can apply the between rule:


'users' => 'array|between:3,10'


Laravel Validation for Array Size:


When you have to validate an array with exactly three users you can apply the size rule:


'users' => 'array|size:3'



Laravel Validation with Controller Code:


<?php

namespace App\Http\Controllers;   

 

use Illuminate\Http\Request;

use App\Models\User;

use Illuminate\View\View;

use Illuminate\Http\RedirectResponse;

    

class UserController extends Controller

{

    /**

     * Show the application dashboard.

     *

     * @return \Illuminate\Http\Response

     */

    public function create(): View

    {

        return view('createUser');

    }

        

    /**

     * Show the application dashboard.

     *

     * @return \Illuminate\Http\Response

     */

    public function store(Request $request): RedirectResponse

    {

        $request->validate([

            'users' => 'array|between:3,10'

        ]);

        return back()->with('success', 'User created successfully.');

    }

}


I hope this will help you in array validation. If you have any doubt please let me know in the comments.