How should I validate a user object being updated by another user in Laravel?

I have a Laravel application where a superadmin user can edit other users.

Please mind that superadmin should be able to edit user's password too. Since I can't really show the password to the people ( it is hashed anyway ) I just show an empty input field for the password. What is the best way to validate this user object?

My form looks like this:

<form class="form-horizontal" method="post" action="{{ route('update_user') }}">
    @csrf
    <input type="hidden" name="user_id" value="{{ $user->id }}">
    <input type="text" name="name" value="{{ $user->name }}">
    <input type="password" name="password" >
    <button type="submit">
</form>

My rules in FormRequest looks like this:

public function rules()
{
    $userId = $this->input('user_id');
    return [
        'name' => 'sometimes|required|string|max:255',
        'password' => 'sometimes|required|string|min:6|confirmed'
    ];
}
  • The scenario is that superadmin edits just the name field and submits the form.
  • Password is recieved as null.
  • So the password rule gives an error.

I can handle this by unsetting the password value on the request if it is null. But I sincerely believe it is a lame way to do it. Is there a better way to achieve this?

2 answers

  • answered 2018-04-14 16:01 Muhammad Nauman

    I hope this works:

    public function rules()
    {
       $userId = $this->input('user_id');
       return [
           'name' => 'required_if:password,null|string|max:255',
           'password' => 'required_if:name,null|string|min:6|confirmed'
       ];
    }
    

    In this way you can validate both the fields separately. Empty request is not acceptable. It should have either of the two values.

  • answered 2018-04-14 17:09 ab_

    Try this..

    public function rules()
    {
        $userId = $this->input('user_id');
        return [
            'name' => 'nullable|string|max:255',
            'password' => 'nullable|string|min:6|confirmed'
        ];
    }
    

    From laravel doc

    A Note On Optional Fields

    By default, Laravel includes the TrimStrings and ConvertEmptyStringsToNull middleware in your application's global middleware stack. These middleware are listed in the stack by the App\Http\Kernel class. Because of this, you will often need to mark your "optional" request fields as nullable if you do not want the validator to consider null values as invalid.