Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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.

about 4 years ago · Santiago Trujillo Report

0

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);
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!