Miljan Rakita
Miljan Rakita

Reputation: 1533

Laravel: FormRequest does not return only validated data

i got object with some validationl, and the request validated method returns even fields that are not in validation rules. Here is how my validation class looks like.

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    return [
        'terminal' => ['required'],
        'terminal.followings' => ['boolean']
    ];
}

And this is how my json body on request looks like.

{
    "client" : {
        "pk" : "2128436070",
        "username" : "miljan_rakita",
        "daily_following" : 1000
    },
    "terminal" : {
        "followings" : true,
        "followingasdad" : "asdasdas",
        "followers" : false,
        "exact_account" : true
    }
}

From this validation, i expect to get only this object:

{
    "terminal" : {
        "followings" : true,
    }
}

But when i dd the validated data:

public function store(Test $request)
{
    dd($request->validated());
}

Response is full terminal object, even non validated items.

array:1 [▼
        "terminal" => array:4 [▼
            "followings" => true
            "followingasdad" => "asdasdas"
            "followers" => false
            "exact_account" => true
        ]
    ]

So i expect to get only terminal object with followings field with it. But i get all other fields that are in terminal object.

I can pull out only items i need from array, but i would like to know why i don't get only validated items.

Upvotes: 2

Views: 1671

Answers (1)

PtrTon
PtrTon

Reputation: 3835

The form validation only checks if the incoming request does at least contain all required values, so the request data you receive is as expected. Having said so you'd like to adjust the incoming data, which can be done in the latest release; laravel v5.8.33. You can do so by implementing the passedValidation() method in your formrequest (Test in your case).

public function passedValidation()
{
    // '$this' contains all fields, replace those with the ones you want here
}

Upvotes: 1

Related Questions