kjdion84
kjdion84

Reputation: 10064

Laravel only update if not null

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()?

Upvotes: 9

Views: 18643

Answers (2)

Alexey Mezenin
Alexey Mezenin

Reputation: 163978

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.

Upvotes: 22

oseintow
oseintow

Reputation: 7421

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);

Upvotes: 3

Related Questions