How to Re-Use The Same FormRequest Class for Both store() and update() Actions

In your CRUD classes, it's good practice to use FormRequest classes for validation. Usually people create one for store() method and one for update() - something like StoreUserRequest and UpdateUserRequest. But maybe it's possible to combine them into one?

It's pretty easy, actually.

Let's look at a typical FormRequest file:

<?php

namespace App\Http\Requests;

use App\User;
use Illuminate\Foundation\Http\FormRequest;

class StoreUserRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'name' => 'required',
            'email' => 'required',
            'password' => 'required|min:6',
        ];
    }
}

As you can see, method rules() should return an array of fields. So we can re-use the same array for the update() method, with a little modification.

Let's imagine a typical scenario - while creating a user, we must define password field, but in edit form - the password is not required (unless you want to change it). So, how to make password field required only in case of create form?

Luckily, inside of rules() method we have access to check HTTP method that has been used. As we know, store() comes with POST method, and update() uses PUT method.

So, we can do something like this:

public function rules()
{
    $rules = [
        'name' => 'required',
        'email' => 'required',
    ];

    if ($this->getMethod() == 'POST') {
        $rules += ['password' => 'required|min:6'];
    }

    return $rules;
}

And then, we can reuse the same FormRequest class in both methods, in the Controller:

public function store(StoreUserRequest $request)
{
    // ...
}

public function update(StoreUserRequest $request, User $user)
{
    // ...
}

For more information about FormRequest classes, read official Laravel documentation.

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 58 courses (1056 lessons, total 44 h 09 min)
  • 78 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials