Home / Snippets / Validating Array in Laravel Request
Validating Array in Laravel Request cover

Validating Array in Laravel Request

612

2 years ago

0 comments

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!
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this