title: Failed to load resource: the server responded with a status of 422 (Unprocessable Entity) in Angular-7 and Laravel-5.8
body: <p>I am developing a client portal application using Angular-7 as frontend and Laravel-5.8. I am using Larave Spatie for User Management. I have these three tables:</p>
  
  <p>Laravel:</p>
  
  <pre><code>CREATE TABLE `client` (
  `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  `client_id` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `client_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
  
  
  CREATE TABLE `users` (
  `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `client_id` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
  </code></pre>
  
  <p>From the tables above, I have two classes: User and Client. </p>
  
  <ol>
  <li><p>Each user belong to a client, but not more that one. </p></li>
  <li><p>client_id in client is also a Primary Key.</p></li>
  </ol>
  
  <p>UsersController</p>
  
  <pre><code>&lt;?php
  namespace App\Http\Controllers;
  use Illuminate\Http\Request;
  use Illuminate\Support\Facades\Auth;
  use Carbon\Carbon;
  use App\User;
  use App\Client;
  use Spatie\Permission\Models\Role;
  use Spatie\Permission\Models\Permission;
  use App\Notifications\SignupActivate;
  use Avatar;
  use Storage;
  use App\Guardian;
  
  class UsersController extends Controller
  {
  
  public function update(Request $request, $id)
  {
      if(!Auth::user()-&gt;hasPermissionTo('Edit Users') &amp;&amp; !Auth::user()-&gt;id==$id)
          return response()-&gt;json([ "message" =&gt; 'User do not have permission'], 401);
      $rules = [
          'name' =&gt; 'required|min:2',
          'client_id' =&gt; 'required'
      ];
  
      $this-&gt;validate($request, $rules);
  
      $user = User::findOrFail($id);
  
  
      if($request-&gt;role){
          foreach($user-&gt;roles as $role)
              $user-&gt;removeRole($role);
          foreach($request-&gt;role as $role)
              $user-&gt;assignRole($role);
      }
  
      $user-&gt;name = $request-&gt;name;
      $user-&gt;save();
  
      return response()-&gt;json(['data' =&gt; $user], 201);
  }
  }
  </code></pre>
  
  <p>ClientController.php</p>
  
  <pre><code>    public function clientAll(){
      return response()-&gt;json(Client::all());
  }
  </code></pre>
  
  <p>api.php</p>
  
  <pre><code>Route::group([
  'middleware' =&gt; 'auth:api'
  ], function () {
  Route::get('users/profile', 'UsersController@profile');
  Route::resource('users', 'UsersController', ['only' =&gt;        ['index', 'show', 'store', 'update', 'destroy']]);
  Route::post('users/pause', 'UsersController@pause');
  });
  
  Route::group([
  'middleware' =&gt; 'auth:api'
  ], function () {
  Route::get('client/clientall', 'ClientController@clientAll');
  Route::resource('client', 'ClientController', ['only' =&gt;    ['index', 'show', 'store', 'update', 'destroy']]);
  });
  </code></pre>
  
  <p>During update of the user date, I want to have a dropdown select option populated with client_id/client_name. So that I can updated the user table with client_id.</p>
  
  <p><a href="https://i.stack.imgur.com/gvDd1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gvDd1.png" alt="edit user"></a></p>
  
  <p>Angular</p>
  
  <p>user.component.ts</p>
  
  <pre><code>import { Component, OnInit } from '@angular/core';
  import { HttpClient } from '@angular/common/http';
  import { ApiService } from '../../../shared/services/api.service';
  import { SnotifyService } from 'ng-snotify';
  import { Router, ActivatedRoute } from '@angular/router';
  import {NgbPaginationConfig} from '@ng-bootstrap/ng-bootstrap';
  
  import { TokenService } from '../../../shared/services/token.service';
  import { RolesCheckService } from 'src/app/shared/services/roles-check.service';
  
  @Component({
    selector: 'app-users',
    templateUrl: './users.component.html',
    styleUrls: ['./users.component.scss']
  })
  export class UsersComponent implements OnInit {
  
  users = null;     //Store Users Data
  roles = null;     //Store all roles Data
  clients = null;
  
  public error = {
  'role' : null,
  'email' : null,
  'client_id' : null,
  'name' : null,
  'password' : null
  };
     //Form errors
   keyword = null;   //Current Search Keyword
   pagination = {    //Current Pagination data
  'page' :  '1',
  'max' : '10'
  }
   role = null;
   User = 'User';
  
  data = {          //User Update Data
   "id" : null,
   "name" : null,
   "client_id" : null,
   "role" : []
  }
  
  form = {         //New User add Data
    'name' : null,
    'email' : null,
    'client_id' : null,
    'password' : null,
    'password_confirmation' : null,
    'role' : []
   }
  
   headers = {     //Token for API Authorization
   'Authorization' : this.token.get(),
   'X-Requested-With' : 'XMLHttpRequest'
    }
  
    sortData = {        //Current Sort Data
     "col" : null,
     "order" : null
    }
  
   isSuperAdmin = false;
  
   constructor(private roleManage : RolesCheckService , private route : ActivatedRoute, private pg:   NgbPaginationConfig, private token : TokenService, private http : HttpClient, private router :    Router,private api : ApiService, private notify : SnotifyService) {
    pg.boundaryLinks = true;
    pg.rotate = true;
    }
  
   ngOnInit() {
  
   console.log('isSuperAdmin: ' + this.roleManage.isSuperAdmin);
   this.isSuperAdmin = this.roleManage.isSuperAdmin;
   this.route.queryParams.subscribe(params =&gt; {
     if(params['role']){
      this.role = params['role'];
      this.User = this.role;
  
    } else {
      this.User = 'User';
      this.role = '';
    }
  })
  this.notify.clear();
  this.notify.info("Loading...", {timeout: 0});
  
  if(this.keyword) {
    this.api.get('users?search=' + this.keyword + '&amp;page=' + this.pagination.page + '&amp;sort=' + this.sortData.col + '&amp;order=' + this.sortData.order + '&amp;role=' + this.role, this.headers).subscribe(
      data =&gt; this.datahandler(data),
      error =&gt; { this.notify.clear(); console.log(error); this.notify.error(error.error.message); }
    );
  } else {
    this.api.get('users?page=' + this.pagination.page + '&amp;sort=' + this.sortData.col + '&amp;order=' + this.sortData.order + '&amp;role=' + this.role, this.headers).subscribe(
      data =&gt; this.datahandler(data),
      error =&gt; { console.log(error); this.notify.error(error.error.message); }
    );
  }
  this.api.get('role', this.headers).subscribe(
    data =&gt; { console.log(data); this.roles=data; },
    error =&gt; { console.log(error); this.notify.clear(); this.notify.error(error.error.message); }
  );
  this.api.get('client/clientall', this.headers).subscribe(
    data =&gt; this.clients = data,
    error =&gt; { this.notify.error(error.error.message) }
   );
  }
  
  
   datahandler(data){
    console.log(data.data);
    this.notify.clear();
    this.users = data.data;
    this.pagination.max = data.total;
  }
  
  //sort handler
  sort(col){
   console.log(col);
   if(this.sortData.order=="asc" &amp;&amp; this.sortData.col==col){
    this.sortData.order = "desc"
   } else if(this.sortData.order=="desc" &amp;&amp; this.sortData.col==col){
    this.sortData.order = null;
    col = null;
   } else {
    this.sortData.order = "asc"
   }
   this.sortData.col = col;
   this.ngOnInit();
  }
  
  //Paginate Handling
   paginateClick(page){
    console.log(page);
    this.pagination.page = page;
    this.ngOnInit();
   }
  
   //Serach Handling
   search(){
   this.ngOnInit();
   }
  
  //Pause or Active User Handling
   pause(id){
   this.notify.clear();
   console.log(id);
   var body = {
    "id" : id
   }
   return this.api.post('users/pause', body, this.headers).subscribe(
    data =&gt; {this.notify.info("Success", {timeout: 2000}); this.ngOnInit(); },
    error =&gt; this.notify.error(error.message, {timeout: 0})
    );
   }
  
  //User edit Handling
  edit(id){
   this.notify.clear();
   this.data.name = null;
   this.data.role = [];
   this.api.get('users/'+id, this.headers).subscribe(
     data =&gt; this.editDataHandler(data),
     error =&gt; this.notify.error("User Not Found", {timeout: 0})
   );
   this.data.id = id;
   var modal = document.getElementById('editModal');
   modal.style.display = "block";
  }
  
  editDataHandler(data){
   console.log(data);
  this.data.name = data.name;
  for(var i=0; i&lt;data.roles.length; i++)
    this.data.role.push(data.roles[i].name);
  }
  
   checkbox(event){
     if(event.srcElement.checked){
     this.data.role.push(event.srcElement.name);
    } else {
     var index =this.data.role.indexOf(event.srcElement.name);
     this.data.role.splice(index, index+1);
    }
    console.log(this.data.role);
   }
  
  editsubmit(){
    this.notify.clear();
    this.notify.info("Wait...", {timeout: 0});
    this.api.put('users/'+this.data.id, this.data, this.headers).subscribe(
     data =&gt; {
      this.notify.clear();
      this.notify.info("User Updated Successfully", {timeout: 2000});
      this.ngOnInit();
      this.closeEditModal();
    },
    error =&gt; { this.notify.clear(); this.error = error.error.errors; }
   );
  }
  
  closeEditModal(){
   this.error = {
    'role' : null,
    'email' : null,
    'client_id' : null,
    'name' : null,
    'password' : null
   };
   var modal = document.getElementById('editModal');
   modal.style.display = "none";
  }
  
  //User delete Handling
  delete(id){
   this.notify.clear();
   this.notify.warning('Are you sure you want to detele this User?', 'Delete User', {
    timeout: 0,
    showProgressBar: false,
    closeOnClick: true,
    pauseOnHover: true,
    buttons: [
      {text: 'Yes', action: () =&gt; {
        var headers = {
          'Authorization' : this.token.get()
        }
        return this.api.delete('users/'+id, headers).subscribe(
          data =&gt; {this.notify.info("Success", {timeout: 2000}); this.ngOnInit(); },
          error =&gt; this.notify.error(error.message, {timeout: 0})
        );
      }, bold: false},
      {text: 'No'}
    ]
   });
  }
  
  //New User add Handling
  add(){
   this.notify.clear();
  
   this.form.name = null;
   this.form.email = null;
   this.form.password = null;
   this.form.password_confirmation = null;
   this.form.role = [];
  
   var modal = document.getElementById('addModal');
   modal.style.display = "block";
  }
  
  
  checkboxAdd(event){
    if(event.srcElement.checked){
      this.form.role.push(event.srcElement.name);
    } else {
      var index =this.form.role.indexOf(event.srcElement.name);
      this.form.role.splice(index, index+1);
    }
    console.log(this.form.role);
   }
  
    addModalSubmit(){
     this.notify.clear();
     this.notify.info("Wait...", {timeout: 0});
     this.api.post('users', this.form, this.headers).subscribe(
      data =&gt; {
       this.notify.clear();
       this.notify.info("User Added Successfully", {timeout: 2000});
      this.ngOnInit();
      this.closeAddModal();
     },
     error =&gt; { this.notify.clear(); this.error = error.error.errors; }
    );
  
   }
  
   closeAddModal(){
    this.error = {
     'role' : null,
     'email' : null,
     'client_id' : null,
     'name' : null,
     'password' : null
    };
   var modal = document.getElementById('addModal');
   modal.style.display = "none";
  }
  }
  </code></pre>
  
  <p>user.component.html</p>
  
  <pre><code>&lt;!-- The Modal --&gt;
  &lt;div id="addModal" class="modal" style="background-color: rgb(0,0,0); background-color: rgba(0,0,0,0.4);"&gt;
  
  &lt;div class="modal-dialog" role="document"&gt;
    &lt;div class="modal-content"&gt;
      &lt;div class="modal-header"&gt;
  
        &lt;button type="button" class="close" (click)='closeAddModal()'&gt;
          &lt;span aria-hidden="true"&gt;&amp;times;&lt;/span&gt;
        &lt;/button&gt;
      &lt;/div&gt;
      &lt;div class="modal-body"&gt;
          &lt;div class="alert alert-danger" [hidden]="!error.role"&gt;
              {{ error.role }}
            &lt;/div&gt;
          &lt;div class="alert alert-danger" [hidden]="!error.email"&gt;
              {{ error.email }}
            &lt;/div&gt;
            &lt;div class="alert alert-danger" [hidden]="!error.name"&gt;
                {{ error.name }}
              &lt;/div&gt;
            &lt;div class="alert alert-danger" [hidden]="!error.password"&gt;
                {{ error.password }}
              &lt;/div&gt;
        &lt;form #editUserForm=ngForm&gt;
  
            &lt;div class="form-group"&gt;
                &lt;label for="name"&gt;Name&lt;/label&gt;
              &lt;input type="name" name="name" id="inputName" class="form-control" placeholder="Name" [(ngModel)]="form.name" required&gt;
            &lt;/div&gt;
            &lt;div class="form-group"&gt;
                &lt;label for="name"&gt;Email&lt;/label&gt;
                &lt;input type="email" name="email" id="inputEmail" class="form-control" placeholder="Email address" required [(ngModel)]="form.email"&gt;
              &lt;/div&gt;
              &lt;div class="form-group"&gt;
                  &lt;label for="name"&gt;Role&lt;/label&gt;
                  &lt;div *ngFor="let role of roles"&gt;
                      &lt;input type="checkbox" name="{{ role.name }}" value="{{ role.name }}" (change)="checkboxAdd($event)"&gt; {{ role.name }}
                  &lt;/div&gt;
              &lt;/div&gt;
              &lt;div class="form-group"&gt;
                  &lt;label for="name"&gt;Password&lt;/label&gt;
            &lt;input type="password" name="password" id="inputPassword" [(ngModel)]="form.password" class="form-control" placeholder="Password" required&gt;
          &lt;/div&gt;
  
          &lt;div class="form-group"&gt;
              &lt;label for="name"&gt;Password Confirmation&lt;/label&gt;
            &lt;input type="password" name="password_confirmation" id="inputPasswordConfirm" [(ngModel)]="form.password_confirmation" class="form-control" placeholder="Re enter Password" required&gt;
          &lt;/div&gt;
        &lt;/form&gt;
  
      &lt;/div&gt;
      &lt;div class="modal-footer"&gt;
        &lt;button type="button" class="btn btn-primary" (click)='addModalSubmit()' [disabled]="!editUserForm.valid"&gt;Save changes&lt;/button&gt;
        &lt;button type="button" class="btn btn-secondary" (click)='closeAddModal()'&gt;Close&lt;/button&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p></p>
  
  <p>When I clicked on submit button (Save changes) I got this error message:</p>
  
  <blockquote>
    <p>Failed to load resource: the server responded with a status of 422 (Unprocessable Entity) </p>
  </blockquote>
  
  <p>When I checked the developer's tool at the network, I found this error message:</p>
  
  <p><a href="https://i.stack.imgur.com/NTPJo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NTPJo.png" alt="network error"></a></p>
  
  <p>How do I resolve this issue?</p>