To validate at least one item in a form array with Laravel validation, I use a custom validation rule.
Custom validation rules are very easy to set up and Laravel provides this feature to manage our custom form validation rules.
We can use the following artisan command to create a new validation rule class.
php artisan make:rule ValidateArrayElement
It will generate the rule file in the app/rules directory. Here we can use passes() method to validate our inputs.
<?php namespace App\Rules; use Illuminate\Contracts\Validation\Rule; class ValidateArrayElement implements Rule { /** * Create a new rule instance. * * @return void */ public function __construct() { // } /** * Determine if the validation rule passes. * * @param string $attribute * @param mixed $value * @return bool */ public function passes($attribute, $value) { return count($value) > 0; } /** * Get the validation error message. * * @return string */ public function message() { return 'At least one element is required!'; } }
We can also use array_filter() or can manipulate the array if needed to do so. Then can apply the rule and return the boolean response of this validation.
Even we can set the error message for this rule here with the message() method.
Now we can use this rule where we want. Like this
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use App\Rules\ValidateArrayElement; class ServiceRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'name' => 'required|max:191', 'service_type' => 'required', ‘Services’ => [new ValidateArrayElement() ] ]; } }
Hope you found this article useful. Happy LaraCoding.
Today we are going to learn about managing multiple PHP versions on ubuntu with xampp.…
Let's understand about how to use coding to improve your website's SEO. In today’s computerized…
Let's understand the most important linux commands for web developers. Linux, as an open-source and…
Today we are going to discuss top 75+ Laravel interview questions asked by top MNCs.Laravel,…
Today we will discuss about the Mailtrap integration with laravel 10 .Sending and receiving emails…
Today we are going to integrate FCM (Firebase Cloud Messaging) push notifications with ionic application.Firebase…