0

I'm trying to update a specified resource in my laravel application using data submitted through a classic form, using PUT/POST method:

Model::find($id)->update($request->all());

This works fine, except the case where I submit the form with an empty input. Then I'll have all values in my request except the empty input's data, so the updating process isn't complete.

I know I can check if each request parameter exists and if it doesn't, assign it a NULL value but I'm trying to avoid that and I want to know if Laravel retrieves empty data that could be access through Request.

3
  • if (!empty($request->all())) ?? Commented Jul 11, 2018 at 15:19
  • I want to be able to access empty data as well, right know $request->all() only retrieves populated form data Commented Jul 11, 2018 at 15:32
  • Answered here: stackoverflow.com/questions/51298213/… Commented Jul 16, 2018 at 8:03

3 Answers 3

1
//remove the _token from the request
$data = request()->except(['_token']);
// then with array_filter remove empty array values from $data
$result = array_filter($data);
//finally update your record
Model::find($id)->update($result)

EDIT :

You want to keep all the fields even the null ones ?

Add rules to your request and mark your "optional" request fields as nullable if you do not want the validator to consider null values as invalid, here is an example of rules :

public static $rules = [
'first_name' => 'nullable|string',
'last_name' => 'nullable|string'
];
Sign up to request clarification or add additional context in comments.

3 Comments

$result = array_filter($request->all()) would be easier.
yes ! if the Model does not contain a column named "_token " otherwise it will be a serious problem :p
Why would I remove empty values when I don't even get them? I don't want to remove empty values, I just want empty values to be accessible through $request the same way non-empty values are!
0

Check with array_filter(request()->all()). i.e.

Model::find($id)->update(request()->all()):

Comments

0

Instead of using request->all() set the fields explicitly with a fallback. something like: Model::find($id)->update([ 'this' => $request->this ?? '', 'that' => $request->that ?? '', ]);

A little more cumbersome but it will get the job done.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.