CakePHP 3.4, How to change Request data programmaticly

In version 3.4 the access to the public $data variable in Cake\Http\ServerRequest is deprecated.
We can read the POST data using

Cake\Http\ServerRequest::getData($name, $default = null)

But how can I change the data. Now I use

$request->data[‘username’] = $request->data[‘email’];

But it is deprecated and will be not possible in cake 4.0

Would also like to know the answer to this. I’m busy with an app that I keep updating because I don’t want to sit in a situation similar to now where I need to update a 2.1.x app to 3.x.x.

The simple answer is that you don’t, can’t and shouldn’t. The request is an immutable state that you have received from a client.

What particular use case do you have where you think you need to change the request data?

1 Like

I don’t have a specific use case for it. Just thought I’d ask before setting the data to a variable and manipulating it there.

Sometimes you need to modify request data before saving it to the db

That’s fine, but, set it to a variable and manipulate the variable. You should not be manipulating the request object directly anymore.

Yeah that’s the only solution. Thanks for the feedback. Suppose this also answers @ironbone’s question…

In my situation I use a plugin which needs to get the username and the email. Because I want to use the email as username I just want to ask the user for the email (but not for the username) and then set the username to be the email and pass the data to the plugin.

My solution was to have a hiden input for the username then set it in on submit using JavasScript and then add the validation email=username
With setting

$request->data[‘username’] = $request->data[‘email’];

it was just simpler.

@dakota Having said that, may I ask is it possible to unset the request data array to prevent resubmission? thanks.

1 Like

I have another use case for modifying the request data.

I’m allowing people to post to one of my sites using a simple API Format. I want my controllers to only access request->data, but when they do a raw data post with JSON directly to the controller, I have to access the data using file_get_contents(‘php://input’).

I’ve been trying to decode the data and replace request->data with the decoded raw data. Unfortunately I can’t do this directly.