The Problem
In most cases create and edit form for any resource is same however there might be slightly different validation rule for create case and edit case. This post helps you in using same Form Request class for both create and edit case.
Lets say you are verifying a user create/edit form. For user create form user has to provide his/her image but for update its inconvenient to provide image all the time and in edit case image is optional. To handle this in same FormRequest class use this:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UserRequest 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()
{
// This is a PUT or PATCH case so image is not required however laravel image validation is applied if user selects an image
$rules = [
'name' => 'required',
'image' => 'nullable|image',
'email' => 'required|email'
];
// This is a create case and notice image field is required
if($this->getMethod() == 'POST') {
$rules = [
'name' => 'required',
'image' => 'required|image',
'email' => 'required|email'
];
}
return $rules;
}
}
In above code example, image field is required in create case but optional in edit case.