change value of $request before validation in laravel 5.5
Asked Answered
S

3

9

I have a form in route('users.create').

I send form data to this function in its contoller:

public function store(UserRequest $request)
{

    return redirect(route('users.create'));
}

for validation I create a class in

App\Http\Requests\Panel\Users\UserRequest;

class UserRequest extends FormRequest
{
    public function rules()
    {
        if($this->method() == 'POST') {
             return [
                 'first_name' => 'required|max:250',

It works.

But How can I change first_name value before validation (and before save in DB)?

(Also with failed validation, I want to see new data in old('first_name')

Update

I try this:

 public function rules()
    {
     $input = $this->all();


     $input['first_name'] = 'Mr '.$request->first_name;
     $this->replace($input);

     if($this->method() == 'POST') {

It works before if($this->method() == 'POST') { But It has not effect for validation or for old() function

Sharisharia answered 6/10, 2017 at 23:45 Comment(0)
S
31

Override the prepareForValidation() method of the FormRequest.

So in App\Http\Requests\Panel\Users\UserRequest:

protected function prepareForValidation()
{
    if ($this->has('first_name'))
        $this->merge(['first_name'=>'Mr '.$this->first_name]);
}
Siena answered 26/2, 2018 at 7:38 Comment(0)
Z
1

Simply use

$request->merge(['New Key' => 'New Value']);

In your case it can be as follows for saving

$this->merge(['first_name'=>'Mr '.$this->first_name]);
Zoogeography answered 29/1, 2022 at 16:17 Comment(0)
S
0

Why not doing the validation in the controller? Than you can change things before you validate it and doing your db stuff afterward.

public function store(Request $request)
{
    $request->first_name = 'Mr '.$request->first_name;

    Validator::make($request->all(), [
        'first_name' => 'required|max:250',
    ])->validate();

    // ToDo save to DB

    return redirect(route('users.create'));
}

See also https://laravel.com/docs/5.5/validation

Syllabify answered 7/10, 2017 at 0:24 Comment(1)
Is it not possible to do it on my method? Please see my update.Sharisharia

© 2022 - 2024 — McMap. All rights reserved.