skip to Main Content

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


  1. Laravel has a handy isDirty() method on Models, so you can simply check that and update if required:

    $user = auth()->user();
    
    $user->name = $request->input('name');
    $user->telegram = $request->input('telegram');
    
    if ($user->isDirty()) {
      $user->save();
    }
    

    Complete documentation is available here:

    https://laravel.com/docs/8.x/eloquent#examining-attribute-changes

    Login or Signup to reply.
  2. 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 an address but then decides to remove their address. They clear the address field, save the form, are shown a success response and their address 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:

    public function store(Request $request) 
    {
        $request->validate([
            'name' => 'required|string|max:255|min:5',
            'telegram' => 'max:255',
            'discord' => 'max:255'
        ]);
    
        $data = array_filter($request->except('_token'));
        Auth::user()->update($data);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search