Form Request Validation

Creating Form Requests

The generated class will be placed in the app/Http/Requests directory.

php artisan make:request StoreFormValidation

You can use a switch statement for multiple validations.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreFormValidation 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 [
            'title' => 'required|unique:todos',
            'body' => 'required'
        ];*/

        switch ($this->method()) {
            case 'GET':
            case 'DELETE':
            {
                return [];
            }
            case 'POST':
            {
                return [
                    'title' => 'required|unique:todos|max:50',
                    'body' => 'required',
                ];
            }
            case 'PUT':
            case 'PATCH':
            {
                return [
                    'title' => 'required|max:50',
                    'body' => 'required',
                ];
            }            
            default:               
                break;
        }
    }
}

How are the validation rules evaluated?

public function store(StoreFormValidation $request)
{
    // The incoming request is valid...
}

public function update(StoreFormValidation $request, $id)
{
    // The incoming request is valid...
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s