Modify Request Input data before form validation in Laravel

Root User

May 23, 2020

If you are thinking about clean and best way to modify request input data before form validation then laravel has a method called prepareForValidation in formrequest class, where you can modify data as you need.

To illustrate this example, let's suppose that we want to add slug field in request from title before form validation. This is done as shown below in example.

Example:

<?php

namespace App\Application\Front\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Str;

class TaskCreateRequest extends FormRequest
{
    /**
     * Place to Modify data before Laravel Form Validation
     *
     * @return void
     */
    protected function prepareForValidation()
    {
        $this->merge([
            'slug' => Str::slug($this->title),
        ]);
    }

    /**
     * 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 [];
    }
}

The request input data is accessed as class properties, because it extends from FormRequest Class. For example: $this->title is similar to $request->title in controller.

Related Articles