9

Is there a way of condensing the following code into a single update()?:

    $this->validate(request(), [
        'name' => 'required|string|max:255',
        'email' => 'required|string|email|max:255|unique:users,email,'.$id,
        'password' => 'nullable|string|min:6|confirmed',
        'timezone' => 'required|timezone',
    ]);

    $user = User::findOrFail($id);
    $user->update(request()->all());
    if (!empty(request()->input('password'))) {
        $user->update(['password' => bcrypt(request()->input('password'))]);
    }

I want to get rid of the conditional statement for updating the password because I am using a mutator to bcrypt it automatically now. Is there a method like request()->allNotNull()?

3
  • That won't solve your problem, because you still need to bcrypt() your password? Also which version of Laravel are you using? Commented Apr 26, 2017 at 11:07
  • The password is bcrypted with a mutator now....sorry should have mentioned that. Commented Apr 26, 2017 at 12:17
  • 2
    Then @Alexey's answer is perfect. Commented Apr 26, 2017 at 12:31

2 Answers 2

22

You can do this:

$user = User::where('id', $id)->update(request()->all());

Maybe you'll also want to add ->take(1).

Update

In comments you've said you want to get rid of empty fields. Use array_filter():

array_filter($request->all());

If no callback is supplied, all entries of array equal to false will be removed.

Sign up to request clarification or add additional context in comments.

3 Comments

I want to get rid of the conditional statement for updating the password because I am using a mutator to bcrypt it automatically now. Is there a method like request()->allNotNull()?
request does not have a filter method. The request object must be converted to a collection before.
@oseintow silly me. Of course, it doesn't. Updated the answer with array_filer solution which does exactly the same job (filter() uses array_filter()). Thanks.
3

You can try this. Password will be filtered out if password is empty.

$input = collect(request()->all())->filter()->all();

$user = User::where('id', $id)->update($input);

1 Comment

Or just $input = array_filter($request->all()) since al filter() does is using array_filter().

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.