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.
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.
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 hereI hope this short snippet helps and if you need more details then do visit Laravel Validation documentation. Cheers happy coding!