V
V
vladislav9972020-10-14 16:59:16
Laravel
vladislav997, 2020-10-14 16:59:16

How to update only those values ​​that came in?

Tell me how in laravel to update only those values ​​that came in?

There is for example a model with such fields:
title | description | body

I know that you can update it like this:

$post = Post::find($id);
$post->title = '...';
$post->description = '...';
$post->body = '...';

$post->save();

But the trick is that if we send only the title, then the rest will be null.
If I did this from the view, I would store all the values ​​in the value of the inputs in the form and send them all, but the problem is that this is an api, and how can I make sure that only the value of the field that came in changes? I would not want to build a Christmas tree from if-else

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2020-10-14
@vladislav997

$post->fill($request->validated())->save()
Of course, you either need to add fields to the fillable or use forceFill.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question