Laravel CRUD

The theme comes with an out of the box user management app. We have integrated this app using Ajax.


Key Features

  • Show Users
  • Create Users
  • Update Users
  • Delete Users

To access CRUD app, click the Laravel Examples/User Management link in the left sidebar or add /laravel/user-management to the URL.


Show Users

The first thing you will see is a list of existing users. We have used Datatable in our app. Datatable provides ajax support to perform CRUD in the database.

Here you can see how we implemented datatable with Laravel.

<table class="datatables-users table">
  <thead class="table-light">
    <tr>
      <th></th>
      <th>Id</th>
      <th>User</th>
      <th>Email</th>
      <th>Verified</th>
      <th>Actions</th>
    </tr>
  </thead>
</table>

In datatable, We have used processing: true and serverSide: true options to handle pagination, search, and page length from the server-side.

Note: We have initialized datatables with column options to achieve better UI for User management app

// ajax setup
$.ajaxSetup({
headers: {
  'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});


var dt_user = dt_user_table.DataTable({
  processing: true,
  serverSide: true,
  ajax: {
    url: baseUrl + 'user-list',
    dataSrc: function (json) {
      ids = 0;
      return json.data;
    }
  },
  ...
  ...
        return data ? $('<table class="table"/><tbody />').append(data) : false;
      }
    }
  }
});

We have created a resource controller to handle all the create, read, update, and delete ('CRUD') actions. You can find this resource controller at app -> Http -> Controllers -> laravel_example -> UserManagement.php location.

In UserManagement Controller, we have a public function called index which handles the datatable's Ajax call to retrieve data.

/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
  $columns = [
    1 => 'id',
    2 => 'name',
    3 => 'email',
    4 => 'email_verified_at',
  ];

  ...
  ...

  if ($data) {
    return response()->json([
      'draw' => intval($request->input('draw')),
      'recordsTotal' => intval($totalData),
      'recordsFiltered' => intval($totalFiltered),
      'code' => 200,
      'data' => $data,
    ]);
  } else {
    return response()->json([
      'message' => 'Internal Server Error',
      'code' => 500,
      'data' => [],
    ]);
  }
}

We have a resource route that points to the resource Controller.

use App\Http\Controllers\laravel_example\UserManagement;

Route::resource('/user-list', UserManagement::class);

Create/Update Users

You can add new ones by clicking the Add New User button (above the table on the right). On the Add user right sidebar, you will find a form that allows you to fill out the user`s name, email, contact, company, country, role, and plan. All pages are generated using blade templates.

We had provided an update/edit icon to update the user's information.

<!-- Offcanvas to add new user -->
<div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasAddUser" aria-labelledby="offcanvasAddUserLabel">
  <div class="offcanvas-header">
    <h5 id="offcanvasAddUserLabel" class="offcanvas-title">Add User</h5>
    <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
  </div>
  <div class="offcanvas-body mx-0 flex-grow-0">
    <form class="add-new-user pt-0" id="addNewUserForm">
      ...
      ...
    </form>
  </div>
</div>

When we click on the update/edit icon. We are performing an Ajax GET request to retrieve the user.

// edit record
$(document).on('click', '.edit-record', function () {
  var user_id = $(this).data('id');

  // changing the title of offcanvas
  $('#offcanvasAddUserLabel').html('Edit User');

  // get data
  $.get(`${baseUrl}user-list\/${user_id}\/edit`, function (data) {
    $('#user_id').val(data.id);
    $('#add-user-fullname').val(data.name);
    $('#add-user-email').val(data.email);
  });
});

The above GET request is handled by the edit function of the controller.

/**
* Show the form for editing the specified resource.
*
* @param  int  $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
  $where = ['id' => $id];

  $users = User::where($where)->first();

  return response()->json($users);
}

We are validating create/update form using the formValidation javascript plugin. After successfully validating the form, we perform an Ajax POST request to create/update the user.

// user form validation
const fv = FormValidation.formValidation(addNewUserForm, {
  fields: {
    name: {
      validators: {
        notEmpty: {
          message: 'Please enter fullname'
        }
      }
    },
   ...
   ...
    }
  });
});

In the UserManagement controller, the store function handles update/create requests.

/**
* Store a newly created resource in storage.
*
* @param  \Illuminate\Http\Request  $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
  $userID = $request->id;

  if ($userID) {
    // update the value
    $users = User::updateOrCreate(
      ['id' => $userID],
      ['name' => $request->name, 'email' => $request->email]
    );

    // user updated
    return response()->json('Updated');
  }
  else{
    ...
    ...
  }
}

Delete Users

To delete the user, we have provided a delete icon.

We have used sweetalert2 to get the delete confirmation.

// Delete Record
$(document).on('click', '.delete-record', function () {
  var user_id = $(this).data('id');

  // sweetalert for confirmation of delete
  Swal.fire({
    title: 'Are you sure?',
    text: "You won't be able to revert this!",
    icon: 'warning',
    showCancelButton: true,
    confirmButtonText: 'Yes, delete it!',
    customClass: {
      confirmButton: 'btn btn-primary me-3',
      cancelButton: 'btn btn-label-secondary'
    },
    buttonsStyling: false
  }).then(function (result) {
    ...
    ...
    }
  });
});

In the UserManagement controller, destroy function handles the delete request.

public function destroy($id)
{
  $users = User::where('id', $id)->delete();
}

FAQ

How you handle password for new user created by Add New User button?

In default laravel migration schema,the password is not a nullable field. You must have to provide a password when you create a user.

Handling password is a complex strategy. There are lots of possibilities to handle a password.

We are not getting into these complexities. We provide freedom for the user to handle passwords as per their requirement.

In our CRUD app, we have used a random string generator function to generate a password.

$userID = $request->id;
$users = User::updateOrCreate(
  ['id' => $userID],
  ['name' => $request->name, 'email' => $request->email, 'password' => bcrypt(Str::random(10))]
);

If we discuss a real-world password handling scenario, create a random password while creating a user and send them a mail to reset the password.

How to completely remove CRUD app?

You can remove our CRUD app by following simple steps:

  1. First, remove our user-management.blade.php file. You can find it at views -> content -> laravel-example -> user-management.blade.php location.
  2. Now, Remove the UserManagement.php controller file. You can find it at app -> Http -> Controller -> laravel_example -> UserManagement.php location.
  3. Remove the below mentioned two routes that is pointing to UserManagement.php controller.
  4. use App\Http\Controllers\laravel_example\UserManagement;
    
    // laravel example
    Route::get('/laravel/user-management', [UserManagement::class, 'UserManagement'])->name('laravel-example-user-management');
    Route::resource('/user-list', UserManagement::class);
  5. Remove the name of page from language, menus and search json files.
  6. /lang/{en|fr|de|pt}.json // localization
    
    /resources/menu/{horizontalMenu|verticalMenu}.json // menus
    
    /public/assets/json/{search-horizontal|search-vertical}.json // search
  7. Remove laravel-user-management.js file from resources -> js -> laravel-user-management.js.
  8. Finally, remove the compilation definition from webpack.mix.js file for laravel-user-management.js.
  9. // laravel working crud app related js
    mix.js('resources/js/laravel-user-management.js', 'public/js/');
© 2017- Pixinvent, Hand-crafted & Made with ❤️