codenex's avatar

How to modify request data before saving

Hello guys! I'm trying to find out how I can manipulate the request data from a form prior to saving it to the database. For instance I have a form that has a field for hostname. This field is disabled as the value is being pulled directly from the $_SERVER superglobal gethostbyaddr($_SERVER['REMOTE_ADDR']. Since it is disabled this field does not submit with the form, which is fine. I know I can create a hidden input field with the same value which does work, though it is not secure. Jeffrey Way even stated in his screencast he recommends against doing this.

In the same video he made it seem like I could just assign the value to the request variable like so:

...
...
public function store(Request $request)
{
    $hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);
    $request->hostname = $hostname;

    Systems::create($request->all());
}

Unfortunately this does not work as the $request variable does not show the hostname.

Additionally if I can get this to work then I can use some of the laravel validation rules to make sure that this value is unique in the database. Since hostname is not being found in the $request variable the validation will never work.

Does anyone have an idea on how to get this to work?

0 likes
4 replies
RonB1985's avatar
RonB1985
Best Answer
Level 18

Never tried it myself, but just googled and found:

Request::merge(['New Key' => 'New Value']);

So you can try:

Request::merge(['hostname' => $hostname]);
mstnorris's avatar

Unfortunately this does not work as the $request variable does not show the hostname.

@codenex you just assign the request data to an array (in this case I called it data). Then you add another element to the array with the key "hostname" and the value that is retrieved from calling gethostbyaddr($_SERVER['REMOTE_ADDR']. Lastly, you create the "System" with the $data.

public function store(Request $request)
{
    $data = $request->all();
    $data['hostname'] = gethostbyaddr($_SERVER['REMOTE_ADDR'];

    Systems::create($data);
}

Additionally if I can get this to work then I can use some of the laravel validation rules to make sure that this value is unique in the database. Since hostname is not being found in the $request variable the validation will never work.

Why not use a where clause when you create? See firstOrCreate in the docs.

2 likes
codenex's avatar

Thanks all. All options were valid it seems.

Please or to participate in this conversation.