How to manipulating data before validating it in Laravel Framework

Tibor Hegedűs
1 min readJan 26, 2019

--

Photo by Fatos Bytyqi on Unsplash

There are some situations when we would like to manipulate data before sending it to validator. Let’s look at an example.

<div class="form-group">
<label for="is_free_usage">Enable free usage</label>

<input type="checkbox" name="is_free_usage" id="is_free_usage">
</div>

Great. We have got a checkbox. Now send it to the controller.

public function store(AccountStoreRequest $request)
{
Account::create($request->validated());
return back()->with('success', 'The save is finished.');
}

The validated method is a great method because we get back only the validated data. But if the checkbox is not checked, then the validated method does not contain the checkbox field. So we need manipulation.

<?php

namespace
App\Requests;


use Illuminate\Foundation\Http\FormRequest;

class AccountStoreRequest extends FormRequest
{
public function authorize()
{
return true;
}

public function rules()
{
return [
'is_free_usage' => 'nullable',
];
}

protected function getValidatorInstance()
{
$this->merge([
'is_free_usage' => $this->filled('is_free_usage')
]);
return parent::getValidatorInstance();
}
}

The getValidatorInstance method was done before the validation started. So use the request merge method and fill the checkbox field name with the manipulated value. Now the request()->all() contains the checkbox name and value in every situation.

I hope I helped you.

--

--

Tibor Hegedűs

I’m a freelance developer and I like to build web applications. My experiences: Laravel, Vuejs, Sass, Java Spring Boot, DevOps.