Im making "Update profile" page and there is fields which are Optional and can leave them blank. What is the best way to make this all? If I change name and leave "address" example so it updates name, but address leaving blank. If updating both then both updates? Here is the code example:
public function store(Request $request)
{
$request->validate([
'name' => 'required|string|max:255|min:5',
'telegram' => 'max:255',
'discord' => 'max:255'
]);
$user = Auth::user();
$user->name=$request->name;
$user->telegram=$request->telegram;
$user->save();
}
2
Answers
Laravel has a handy
isDirty()
method on Models, so you can simply check that and update if required:Complete documentation is available here:
https://laravel.com/docs/8.x/eloquent#examining-attribute-changes
You may confuse your users if you specify a field as
optional
but then choose to ignore empty values. Using your example, lets imagine a user has previously provided anaddress
but then decides to remove theiraddress
. They clear theaddress
field, save the form, are shown asuccess
response and theiraddress
is still there. What gives?!If you specify a field as
optional
, allow it to be cleared.That said, in answer to your question, if you want to remove empty values so that they are not used to overwrite existing values, you can use
array_filter
: