skip to Main Content

I have a problem displaying errors message in update modal form. I’m using laravel request for validation and AJAX to submit form inside a modal. I would like to see the error message for each field that are inputted incorrectly. However, I’m getting this error:

The Given data is invalid

I checked the network tab, and I’m seeing the errors there but I can’t figure out why this is not showing in my fields.

Here is my script’s

function updatePassword(e, t)
{
    e.preventDefault();

    const url    = BASE_URL + '/admin/organizations/operators/updatePassword/' + $(updatePasswordForm).find("input[name='id']").val();
    var form_data = $(t).serialize();    

    // loading('show');
    axios.post(url, form_data)
        .then(response => {
            notify(response.data.message, 'success');
            $(updatePasswordModal).modal('hide');
            // roleTable.ajax.reload()
        })
        .catch(error => {
            const response = error.response;
            if (response) {
                if (response.status === 422)
                    validationForm(updatePasswordForm, response.data.errors);
                else if(response.status === 404)
                    notify('Not found', 'error');
                else
                    notify(response.data.message, 'error');
            }
        })
        .finally(() => {
            // loading('hide');
    });
        
}

Here is my Blade file

<form id="updatePasswordForm" onsubmit="updatePassword(event, this)">
      <input type="hidden" name="id" value="">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel"> {{ __('Update Password') }}</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
            <div class="form-group row">
              <label class="col-sm-4 col-form-label required">{{ __('New Password') }}</label>
              <div class="col-sm-8">
                  <div class="row">
                      <div class="col-sm-12">
                          <div class="form-group @error('user.password') error @enderror">
                              <input type="password" class="form-control" id="password"  name="user[password]" placeholder="{{ __('Password') }}" required>
                          </div>
                      </div>
                  </div>
                  @error('user.password')
                    <p class="error-message">{{ $message }}</p>
                  @enderror
              </div>
            </div>
            <div class="form-group row">
              <label class="col-sm-4 col-form-label required">{{ __('Confirm Password') }}</label>
              <div class="col-sm-8">
                  <div class="row">
                      <div class="col-sm-12">
                          <div class="form-group @error('user.password_confirmation') error @enderror">
                              <input type="password" class="form-control" id="confirmPassword" name="user[password_confirmation]" placeholder="{{ __('Confirm Password') }}">
                          </div>
                      </div>
                  </div>
                  @error('user.password_confirmation')
                    <p class="error-message">{{ $message }}</p>
                  @enderror
              </div>
            </div>
        </div>
        <div class="modal-footer justify-content-center">
          <button type="button" class="btn btn-secondary mr-3" data-dismiss="modal">{{ __('Close') }}</button>
          <button type="submit" class="btn btn-primary">{{ __('Save') }} </button>
        </div>
      </div>
    </form>

Here is My Controller:

<?php

namespace AppHttpControllersAdmin;

use AppHttpControllersController;
use AppHttpRequestsAdminOrganizationOperatorUpdatePasswordRequest;
use AppModelsOrganizationOperator;
use IlluminateHttpRequest;
use AppServicesResponse;
use Exception;
use IlluminateSupportFacadesLog;

class OrganizationController extends Controller
{
    public function updateOperatorPassword(OrganizationOperator $operator, UpdatePasswordRequest $request)
    {
        try {
            $data = $request->validated();
            $user = $data['user'];
            // dd($user['password']);
            $operator->update([
                'password' => bcrypt($user['password']),
            ]);
            return Response::success(__('Successfully updated'));
        } catch (Exception $e) {
            Log::error($e->getMessage());
            return Response::error(__('Unable to update'), [], 500);
        }
    }

}

Here is my Request Validation Class:

<?php

namespace AppHttpRequestsAdminOrganizationOperator;

use IlluminateFoundationHttpFormRequest;

class UpdatePasswordRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules()
    {
        return [
            'id' => ['required', 'integer', 'exists:organization_operators,id'],
            'user.password' => ['required', 'string', 'min:8', 'confirmed'],
        ];
    }
}

2

Answers


  1. Chosen as BEST ANSWER

    Finally I solved this problem.

    1. I change my controller

    public function updateOperatorPassword(OrganizationOperator $operator, UpdatePasswordRequest $request) 
    

    TO

    public function updateOperatorPasswordApi(User $user, UpdatePasswordRequest $request) 
    

    AND

    try {
        $data = $request->validated();
        $user = $data['user'];
        // dd($user['password']);
        $operator->update([
            'password' => bcrypt($user['password']),
        ]);
        return Response::success(__('Successfully updated'));
    }
    

    TO

    try {
        $data = $request->validated();
        $user->update([
            'password' => bcrypt($data['password']),
        ]);
        return Response::success(__('Successfully created'));
    }
    

    2. I change my blade file

    <div class="row">
        <div class="col-sm-12">
            <div class="form-group @error('user.password_confirmation') error @enderror">
                <input type="password" class="form-control" id="confirmPassword" name="user[password_confirmation]" placeholder="{{ __('Confirm Password') }}">
            </div>
        </div>
    </div>
    @error('user.password_confirmation')
        <p class="error-message">{{ $message }}</p>
    @enderror
    

    TO

    <div class="form-group">
        <label for="">{{ __('Password') }}</label>
        <input name="password" type="password" class="form-control" id="password" aria-describedby="emailHelp" placeholder="{{ __('Password') }}" required>
        <small class="form-text error-message"></small>
    </div>
    

    AND

    <div class="row">
        <div class="col-sm-12">
            <div class="form-group @error('user.password_confirmation') error @enderror">
                <input type="password" class="form-control" id="confirmPassword" name="user[password_confirmation]" placeholder="{{ __('Confirm Password') }}">
            </div>
        </div>
    </div>
    @error('user.password_confirmation')
        <p class="error-message">{{ $message }}</p>
    @enderror
    

    TO

    <div class="form-group">
        <label for="">{{ __('Confirm Password') }}</label>
        <input name="password_confirmation" type="password" class="form-control" id="password_confirmation" aria-describedby="emailHelp" placeholder="{{ __('Confirm Password') }}" required>
        <small class="form-text error-message"></small>
    </div>
    

  2. First, I think this issue is because you send the request from the client side (which is is ajax/axios). The validation work when you submit to the server side (without ajax/axios) then response validation will display to the blade/html.

    In this case, you must set error to the html manually (with innerHTML or .html() in jquery) using class/id.

    for example this response from the server/api :

    { "error" : {
        "user.password" : ["invalid password"],
        ...
      }
    }
    

    in client side, you need to put that message to html tag in that case with p tag.

    <p id="error-password" ></p>
    
    $('#error-password').html(error["user.password"])
    // or
    $('#error-password').text(error["user.password"])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search