Laravel Validation Using Request.

Aman jain
7 min readJun 17, 2023

--

1. What is Laravel Validation?

Laravel validation is a feature-rich component that helps developers validate user input effortlessly. It provides a fluent and expressive syntax for defining validation rules, enabling you to ensure that the data submitted by users is valid before further processing. Laravel validation integrates seamlessly with form input, JSON requests, and more.

Creating a Request Class:

To perform request validation in Laravel, you need to create a request class. This class extends the Illuminate\Foundation\Http\FormRequest base class and defines the validation rules for the incoming request. You can generate a new request class using the make:request Artisan command:

php artisan make:request StoreUserRequest

This command will create a new StoreUserRequest class in the app/Http/Requests directory.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreUserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return false;
}

/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
//
];
}
}

Let’s discuss this in detail..

public function authorize()
{
return false;
}

This function checks if the current user is authorized to submit the form.

Typically, this function would check if the user has the correct permissions to submit the form.

However, in this case, we allow any logged-in user to submit the form, so we can simply return True.

In other words, this function is used to make sure that only authorized users can submit the form. However, in this case, any logged-in user is authorized to submit the form, so the function simply returns True.

public function rules()
{
return [
//
];
}

The rules() function in Laravel is used to specify the validation rules for each field in a form. It helps ensure that the data entered in the form meets certain criteria or conditions.

Imagine you have a form with fields like name, email, and password. In the rules() function, you would define the rules for each field.

Each field in the form is represented by a key in the array, and the value is a string that specifies the validation rules.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreUserRequest 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|string|max:255',
'email' => 'required|email|unique:users',
'password' => 'required|string|min:8|confirmed', ];
}
}

Here’s what these rules mean in simpler terms:

  • The name field must be filled in and should only contain letters, numbers, and some special characters. It should not exceed 255 characters in length.
  • The email field must be filled in and should be a valid email address. It should also be unique, meaning it should not already exist in the users table of the database.
  • The password field must be filled in and should be at least 8 characters long. It should also match the confirmation password field in the form.

Customize The Error Messages:-

Laravel provides the flexibility to customize error messages for validation rules through the messages() method in the request class. In the example you provided, the messages() method defines custom error messages for different validation rules. Let's break it down:

public function messages()
{
return [
'name.required' => 'The name field is required.',
'name.string' => 'The name field must be a string.',
'name.max' => 'The name field must not exceed 255 characters.',
'email.required' => 'The email field is required.',
'email.email' => 'Please enter a valid email address.',
'email.unique' => 'The email address is already in use.',
'password.required' => 'The password field is required.',
'password.string' => 'The password field must be a string.',
'password.min' => 'The password must be at least 8 characters long.',
'password.confirmed' => 'The password confirmation does not match.',
];
}

In this example, each validation rule is mapped to an appropriate error message. Here’s a breakdown of the mappings:

  • 'name.required' specifies the custom error message for the required rule on the name field.
  • 'name.string' specifies the custom error message for the string rule on the name field.
  • 'name.max' specifies the custom error message for the max rule on the name field.
  • 'email.required' specifies the custom error message for the required rule on the email field.
  • 'email.email' specifies the custom error message for the email rule on the email field.
  • 'email.unique' specifies the custom error message for the unique rule on the email field.
  • 'password.required' specifies the custom error message for the required rule on the password field.
  • 'password.string' specifies the custom error message for the string rule on the password field.
  • 'password.min' specifies the custom error message for the min rule on the password field.
  • 'password.confirmed' specifies the custom error message for the confirmed rule on the password field.

You can further customize the error messages as per your requirements. When the validation fails, Laravel will display these custom error messages if the corresponding rules are not met.

Here’s the complete code with the rules() and messages() functions for the given validation rules:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreUserRequest 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|string|max:255',
'email' => 'required|email|unique:users',
'password' => 'required|string|min:8|confirmed', ];
}

public function messages()
{
return [
'name.required' => 'The name field is required.',
'name.string' => 'The name field must be a string.',
'name.max' => 'The name field must not exceed 255 characters.',
'email.required' => 'The email field is required.',
'email.email' => 'Please enter a valid email address.',
'email.unique' => 'The email address is already in use.',
'password.required' => 'The password field is required.',
'password.string' => 'The password field must be a string.',
'password.min' => 'The password must be at least 8 characters long.',
'password.confirmed' => 'The password confirmation does not match.',
];
}
}

Now , To implement the rules and display validation errors to the user when submitting a form, we need to make changes to the view file and the StoreUserController.php file.

In the view file, we should include the necessary validation rules for each form field. When the form is submitted and validation fails, the corresponding errors will be displayed to the user.

To make this work, we need to update the type-hinted class in the StoreUserController.php file. Currently, we are using the Request class, but we want to use our custom class called StoreUserRequest.

By doing this, when we submit the form in the StoreUserController@store function, the validation rules specified in the StoreUserRequest class will be applied.

So, in the app/Http/Controllers/StoreUserController.php file, replace the Request class with the CreatePostForm class as the type-hinted class for the function.

<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreUserRequest;
use App\Models\User;

class StoreUserController extends Controller
{
public function store(StoreUserRequest $request)
{
// Validation passed, create and store the user
$user = new User();
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->password = bcrypt($request->input('password'));
$user->save();

// Optionally, you can redirect the user to a success page
return redirect()->route('user.success');
}
}

In this example, we have a store method that takes a StoreUserRequest object as a parameter. This custom request class contains the validation rules and logic for validating the user input.

The store method first checks if the validation passed. If it did, it creates a new User object and assigns the input values from the request to the corresponding user properties. The password is hashed using the bcrypt function for security.

After saving the user to the database, you can optionally redirect the user to a success page or perform any other necessary actions.

Note: Make sure to replace StoreUserRequest with the appropriate name of your custom request class that contains the validation rules for user input.

Now we will Show Error in View..

In Laravel, the $errors variable in the view file holds all the validation errors. To access errors for a specific field, use $errors->get('field') to get an array of errors. To retrieve the first error message for a field, use $errors->first('field'). You can check if there are any errors for a field with $errors->has('field'). Use these methods to display validation errors for form fields in your view.

<form action="{{ route('user.store') }}" method="POST">
@csrf

<label for="name">Name:</label>
<input type="text" name="name" id="name">

@if($errors->has('name'))
<div class="alert alert-danger">{{ $errors->first('name') }}</div>
@endif

<label for="email">Email:</label>
<input type="email" name="email" id="email">

@if($errors->has('email'))
<div class="alert alert-danger">{{ $errors->first('email') }}</div>
@endif

<label for="password">Password:</label>
<input type="password" name="password" id="password">

@if($errors->has('password'))
<div class="alert alert-danger">{{ $errors->first('password') }}</div>
@endif

<button type="submit">Submit</button>
</form>
  • The form action is set to the route for storing user data (`user.store`).
  • The `@csrf` directive adds a hidden input field with a CSRF token for security.
  • The `@error` directive is used to check for validation errors for each input field.
  • If there are validation errors, they will be displayed in a red alert box.
  • The `$message` variable within the `@error` directive contains the specific error message for each field.
  • Laravel automatically retrieves the error messages based on the validation rules defined in the `StoreUserRequest` class.
  • Validation errors are displayed next to the corresponding input fields, providing a better user experience.

Laravel’s approach to validation greatly streamlines the development process and helps you maintain a robust and reliable application.

If you want to learn how local Scope works in laravel , so you can read this tutorial:

And if you love the content and want to support more awesome articles, consider buying me a coffee! ☕️🥳 Your support means the world to me and helps keep the knowledge flowing. You can do that right here: 👉 [Buy Me a Coffee](https://buymeacoffee.com/jainaman)

https://medium.com/@amanj0314/laravel-scopes-6c1121980a1d

--

--