Search code examples
laravellaravel-5laravel-5.6laravel-validationlaravel-request

Laravel 5 Form request, require input on create, but optional on edit


I am using laravel 5.6 resources controllers and form request the problem is that i have some inputs that are required on created, but on edit are optionals like file inputs. So i have this form request

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ProgramRequest 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',
            'description.*' => 'required',
            'logo'          => 'required|image|max:3000',
            'logo_alt'      => 'required|image|max:3000'
        ];
    }
}

the fields logo and logo_alt must be sent when creating the program, but when editing it sending a logo is optional.

is there a way to validate both cases with the same form request or i have to create a different form request for editing and for creating?


Solution

  • You can use $this->method() to check which request method has been used and show different rules for each case:

    public function rules()
        {
            switch($this->method())
            {
                case 'GET':
                case 'DELETE':
                {
                    return [];
                }
                case 'POST':
                {
                     return [
                       'name.*'        => 'required',
                       'description.*' => 'required',
                       'logo'          => 'required|image|max:3000',
                       'logo_alt'      => 'required|image|max:3000'
                    ];
                }
                case 'PUT':
                {
                    return [
                       'description.*' => 'required',
                       'logo'          => 'nullable|image|max:3000',
                       'logo_alt'      => 'nullable|image|max:3000'
                    ];
                }
                case 'PATCH':
                {
                    return [];
                }
                default:break;
            }
        }
    

    In this above example the POST will be for your create and the PUT will be for your update.

    Notice I've used nullable for the PUT validation rules, this tells the request object that the field is optional.