Laravel 8 Crud Operations Example

In this post we have learn how to Laravel 8 Crud Operations Example. Also in this post we will learn such as Laravel 8 CRUD Application Tutorial for Beginners, Laravel 8 CRUD Tutorial by Example, Laravel 8 CRUD Tutorial Example Step By Step, laravel 8 crud with image upload, laravel 8 display image ect.

Laravel 8 Crud Operations Example

Step 1: Install Laravel 5.8

In this step, if you haven’t laravel 8 application setup then we have to get fresh laravel 8 application. So run bellow command and get clean fresh laravel 8 application.

composer create-project --prefer-dist laravel/laravel blog

Step 2 : Install Yajra Datatable Package

We need to install yajra datatable composer package for datatable, so you can install using following command:

composer require yajra/laravel-datatables-oracle

After that you need to set providers and alias.

config/app.php

.....

'providers' => [
....
Yajra\DataTables\DataTablesServiceProvider::class,
]

'aliases' => [
....
'DataTables' => Yajra\DataTables\Facades\DataTables::class,
]

.....

route/web.php

<?php

  use Illuminate\Support\Facades\Route;
  use App\Http\Controllers\UserController;

  Route::get("/", [UserController::class, "index"])->name("list");

  Route::get('user', function () {
   return view('crud.form');
 })->name("user");

 Route::get("user_edit/{id}",[UserController::class, "user_edit"]);
 Route::get("user_delete/{id}",[UserController::class, "user_delete"]);
 Route::post("save_user",[UserController::class, "save_user"]);

Create view file : crud/form.blade.php

<!DOCTYPE html>
<html lang="en">
 <head>
  <title>Laravel 8 Crud Operations Example </title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>

 <div class="container">
  <h2 class="text-center">Laravel 8 Crud Operations Example</h2>
  <form action="{{ isset($user->id) ? '../save_user' : 'save_user'}}" method="post" enctype='multipart/form-data'>
  @csrf

   <input type="hidden" id="id" name="id" value="{{ isset($user->id) ? $user->id : ''}}">
   <div class="form-group">
    <label for="email">Email:</label>
    <input type="email" class="form-control" id="email" placeholder="Enter email" name="email" value="{{ isset($user->email) ? $user->email : ''}}">
  </div>
  <div class="form-group">
   <label for="pwd">Password:</label>
   <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pwd" value="{{ isset($user->password) ? $user->password : ''}}">
 </div>

 <div class="form-group">
  <label for="country">Country:</label>
  <select name="country" id="country" class="form-control">
   <option value="india" <?= isset($user->country) && ($user->country== 'india') ? "selected" : "" ; ?>>India</option>
   <option value="srilanka" <?= isset($user->country) && ($user->country== 'srilanka') ? "selected" : "" ; ?>>SriLanka</option>
   <option value="usa" <?= isset($user->country) && ($user->country== 'usa') ? "selected" : "" ; ?>>USA</option>
  </select>
</div>

<div class="form-group">
 <label>Gender : </label>
 <label for="male">Male</label>
 <input type="radio" name="gender" value="male" <?= isset($user->gender) && ($user->gender== 'male') ? "checked" : "" ; ?>>
 <label for="female">Female</label>
 <input type="radio" name="gender" value="female" <?= isset($user->gender) && ($user->gender== 'female') ? "checked" : "" ; ?>>
</div>

<?php 
 if(isset($user->hobbies)){
   $hobbies = explode(',', $user->hobbies);
 }
?>
<div class="form-group">
  <label><strong>Hobbies :</strong></label>
  <label><input type="checkbox" name="hobbies[]" value="Reading" <?= isset($user->hobbies) && in_array("Reading", $hobbies) ? "checked" : "" ; ?>> Reading</label>
  <label><input type="checkbox" name="hobbies[]" value="Writing" <?= isset($user->hobbies) && in_array("Writing", $hobbies) ? "checked" : "" ; ?>> Writing</label>
  <label><input type="checkbox" name="hobbies[]" value="Developing" <?= isset($user->hobbies) && in_array("Developing", $hobbies) ? "checked" : "" ; ?>> Developing</label>
  <label><input type="checkbox" name="hobbies[]" value="Music" <?= isset($user->hobbies) && in_array("Music", $hobbies) ? "checked" : "" ; ?>> Music</label>
  <label><input type="checkbox" name="hobbies[]" value="Dance" <?= isset($user->hobbies) && in_array("Dance", $hobbies) ? "checked" : "" ; ?>> Dance</label>
</div> 


<div class="form-group">
 <label for="photo">Photo:</label>
 <input type="file" class="form-control" id="photo" name="photo">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>

</body>
</html>

Create model file : User.php

<?php

  namespace App;
  use Illuminate\Database\Eloquent\Model;

  class User extends Model
  {

  }

Create controller file :

<?php

  namespace App\Http\Controllers;

  use Illuminate\Http\Request;
  use App\User;
  use DataTables;
  use File;
  class UserController extends Controller
  {

   function index(Request $request){
    if ($request->ajax()) {
    $data = User::latest()->get();
    return Datatables::of($data)
    ->addIndexColumn()
    ->addColumn('action', function($row){

   $btn = '<a href="user" class="edit btn btn-primary btn-sm">+</a>
          <a href="user_edit/'.$row->id.'" class="edit btn btn-warning btn-sm"><i class="fas fa-edit"></i></a>
          <a href="user_delete/'.$row->id.'" class="edit btn btn-danger btn-sm">X</a>
         ';

      return $btn;
   })
   ->addColumn('photo', function ($photo) {
   return '<img src="public/uploads/'.$photo->photo.'" border="0" width="40" class="img-rounded" align="center" />';
})
->rawColumns(['photo','action']) 
->make(true);
}

return view('crud.list');
}

function save_user(Request $request){
  $id = $request->id;
  if(!empty($id)){
  $user = User::find($request->id);

  $hobbies = implode(',', $request->hobbies);
  if($request->hasFile('photo')) {
    if (File::exists(public_path("uploads/{$user->photo}"))) {
       File::delete(public_path("uploads/{$user->photo}"));
    }

   $img = time()."_".$request->photo->getClientOriginalName();
   $request->photo->move(public_path('uploads'), $img);
 }else{
   $img = $user['photo'];
}

$user->email = $request->email;
$user->password = $request->pwd;
$user->country = $request->country;
$user->gender = $request->gender;
$user->hobbies = $hobbies;
$user->photo = $img;
$user->save();
return back();
}else if(empty($id)){

$img = time()."_".$request->photo->getClientOriginalName();
$hobbies = implode(',', $request->hobbies);
$request->photo->move(public_path('uploads'), $img);

$user = new User;
$user->email = $request->email;
$user->password = $request->pwd;
$user->country = $request->country;
$user->gender = $request->gender;
$user->hobbies = $hobbies;
$user->photo = $img;

$user->save();
return back();
}
}

function user_delete($id){
  $user = User::find($id);
  if (File::exists(public_path("uploads/{$user->photo}"))) {
    File::delete(public_path("uploads/{$user->photo}"));
  }
$user->delete();
return redirect()->route('user');
}

function user_edit($id){
  $user["user"] = User::find($id);

  return view("crud.form",$user);
}
}

Create view file : list.blade.php

<!DOCTYPE html>
<html>
 <head>
  <title>Laravel 8 Datatables Tutorial - Web-tuts.com</title>
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
  <link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
  <link href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css" rel="stylesheet">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script> 
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
  <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css" integrity="sha512-HK5fgLBL+xu6dm/Ii3z4xhlSUyZgTT9tuc/hSrtw6uzJOvgRr2a9jyxxT1ely+B+xFAmJKVSTbpM/CuL7qxO8w==" crossorigin="anonymous" />
</head>
<body>

  <div class="container">
   <h1>Laravel 8 Datatables Tutorial <br/> Web-tuts.com</h1>
   <table class="table table-bordered data-table">
    <thead>
     <tr>
      <th>No</th>
      <th>Email</th>
      <th>Password</th>
      <th>Country</th>
      <th>Gender</th>
      <th>Hobbies</th>
      <th>Photo</th>
     <th width="100px">Action</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
 </table>
</div>

</body>

<script type="text/javascript">
 $(function () {

  var table = $('.data-table').DataTable({
    processing: true,
    serverSide: true,
    ajax: "{{ route('list') }}",
    columns: [
      {data: 'DT_RowIndex', name: 'DT_RowIndex'},
      {data: 'email', name: 'email'},
      {data: 'password', name: 'password'},
      {data: 'country', name: 'country'},
      {data: 'gender', name: 'gender'},
      {data: 'hobbies', name: 'hobbies'},
      {data: 'photo', name: 'photo'},
      {data: 'action', name: 'action', orderable: false, searchable: false},
    ]
 });

});
</script>
</html>