How to validate multiple inputs in laravel?

by dalton_moen , in category: PHP Frameworks , 5 months ago

How to validate multiple inputs in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elise_daugherty , 5 months ago

@dalton_moen 

In Laravel, you can use validation rules to validate multiple inputs. Here is an example of how to validate multiple inputs in a Laravel controller:

  1. Define the validation rules in the controller method:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public function store(Request $request)
{
    $rules = [
        'name' => 'required|string',
        'email' => 'required|email',
        'password' => 'required|min:6',
    ];

    $messages = [
        'name.required' => 'Name is required',
        'email.required' => 'Email is required',
        'email.email' => 'Invalid email format',
        'password.required' => 'Password is required',
        'password.min' => 'Password must be at least 6 characters',
    ];

    $this->validate($request, $rules, $messages);

    // If validation passes, continue with storing the data
}


  1. In this example, we have defined validation rules for three inputs: name, email, and password. The validate() method will automatically redirect back with errors if validation fails.
  2. You can also customize the error messages for each input by providing an array of messages in the messages variable.
  3. If validation fails, Laravel will automatically redirect back with the error messages and old input values. You can display these errors in your view using Laravel's @error directive.


By following these steps, you can easily validate multiple inputs in Laravel.