How to validate incoming requests in Laravel

Categorized as Laravel Tagged

Did you know that there are 4 ways to make validation in Laravel for incoming requests? Here they are:

1. Using Request Facades

$request->validate([
  'name' => 'required|max:50',
  'email' => 'required|email|unique:users',  
]);

2. Using Request helper

request()->validate([
  'name' => 'required|max:50',
  'email' => 'required|email|unique:users',  
]);

3. Using Validator Facade

Validator::make($request->all(), [
  'name' => 'required|max:50',
  'email' => 'required|email|unique:users',  
]);

4. Using Form Request

// Run "php artisan make:request UserRequest"
// to generate form request

class UserRequest extends FormRequest
{
  public function rules()
  {
    return [
      'title' => 'required|unique:posts|max:255',
      'body' => 'required',
    ]
  }
}

// In controller you can do something like this:
public function update(UserRequest $userRequest) {
  
}

Leave a reply

Your email address will not be published.