Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel only update if not null

Tags:

php

laravel

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

like image 540
kjdion84 Avatar asked Apr 26 '17 10:04

kjdion84


2 Answers

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.

like image 109
Alexey Mezenin Avatar answered Sep 23 '22 17:09

Alexey Mezenin


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);
like image 29
oseintow Avatar answered Sep 23 '22 17:09

oseintow