Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

adrians's avatar
Level 10

Larevel Precognition Transform data before any validation

Hello everyone. I want to use Laravel Precognition (Inertia/Vue) in a project but i have simple problem. I want to transform the data (just like using inertia transform before any validation). Is there a solution ? Anyone has been in this situation? Thank you!

0 likes
1 reply
LaryAI's avatar
Level 58

In Laravel, you can transform your request data before validation by using a form request or by manually manipulating the request data within your controller method. Since you're using Inertia.js with Vue, you might be sending data through Inertia's request methods, but the transformation process on the server side remains the same.

Here's how you can do it using a form request:

  1. Generate a form request using Artisan:
php artisan make:request TransformDataRequest
  1. In the generated TransformDataRequest class, override the prepareForValidation method to transform the data before validation:
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class TransformDataRequest extends FormRequest
{
    // ...

    protected function prepareForValidation()
    {
        $this->merge([
            'field_name' => $this->transformData($this->field_name),
        ]);
    }

    protected function transformData($value)
    {
        // Perform your transformation logic here
        return $transformedValue;
    }

    public function rules()
    {
        return [
            'field_name' => 'required|your_validation_rules',
            // other validation rules...
        ];
    }
}
  1. Use the TransformDataRequest in your controller method:
public function store(TransformDataRequest $request)
{
    // The $request->field_name will contain the transformed data
    // and it has already passed the validation rules defined in the TransformDataRequest

    // Your logic here...
}

If you prefer to do it directly in the controller without a form request, you can manipulate the request data before calling the validate method:

public function store(Request $request)
{
    $transformedData = $this->transformData($request->input('field_name'));

    $request->merge(['field_name' => $transformedData]);

    $validatedData = $request->validate([
        'field_name' => 'required|your_validation_rules',
        // other validation rules...
    ]);

    // Your logic here...
}

protected function transformData($value)
{
    // Perform your transformation logic here
    return $transformedValue;
}

In both cases, you're essentially intercepting the request data and modifying it before the validation takes place. This allows you to apply any transformations needed to ensure the data is in the correct format for validation and further processing.

Please or to participate in this conversation.