Posts Learn Components Snippets Categories Tags Tools new About
/

Validating Array in Laravel Request

Learn how to validate an array in Laravel requests to ensure that the data is valid and has a value

Created on Nov 14, 2021

17 views

To validate an array in Laravel request you can make use of the "validate()" method available to the request instance of a controller. To validate an array you can use the "asterisk" symbol "*" to check the value in the array.

Defining Laravel Array Validation


For example, you have ArticleController class and it's like below. To validate the value of the incoming request you can use the "name.*" and define the rules such as "required", "string", and unique by calling it "distinct" and also minimum to be 5 characters. Do note that the validation is separated by the pipe "|" symbol so each of the rules will be for its own definition.
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ArticleController extends Controller
{
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            "name"    => "required|array|min:5",
            "name.*"  => "required|string|distinct|min:5",
        ]);

        // your other code logic here
    }
}
Sometimes it's hard to understand the validation so you can break it down into multi-array dimensions like below.
<?php

$rules = [
    "name"    => [
         'required', // input is required
         'array', // input must be an array
         'min:5'  // there must be 5 members in the array
    ],
    "name.*"  => [
         'required', // input is required
         'string',   // input must be of type string
         'distinct', // members of the array must be unique
         'min:5'     // each string must have min 5 characters
    ]
];

$request->validate($rules);

// your other code logic here
I hope this short snippet helps and if you need more details then do visit Laravel Validation documentation. Cheers happy coding!

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components
)