Search code examples
laravellaravel-validation

laravel using validation request with except method


I am using request validation as

php artisan make:request ClientRequest

As you can see, on client edit form if password field is not empty I am able to use $request->validated() method on database update,

However if password field empty(user dont want to change password),

I am not able to use $request->except('password')->validated() method.

I use $request->except() method due to this situation.

Does this pose a security problem?

public function update(ClientRequest $request, Client $client)
{

    $validated = $request->validated();

    if($request->filled('password') )
    {
        Client::whereId($client->id)->update($validated);
    }else{
        Client::whereId($client->id)->update($request->except('password'));
    }

    return redirect('/clients')->with('success', 'success');
}


Solution

  •  Client::whereId($client->id)->update($request->except('password'));
    

    That line is does pose a big security problem especially if you are relying on validation to set fields rather than the fillable attribute. $request->except('password') will return all the other fields that the user submitted so if the user had added something like is_admin => true in the request, you'll end up setting it on the db if it exists.

    You can use \Illuminate\Support\Arr::except() on the validated data to make sure that you are only getting the data you expect. That would change the that particular line to

    Client::whereId($client->id)->update(\Illuminate\Support\Arr::except($request->validated(), 'password'));
    

    PS: You already have the client through route model binding so you don't need to query it you can update that client directly i.e

    $client->update(\Illuminate\Support\Arr::except($request->validated(), 'password'));