[Thực hành] Sử dụng Eloquent Ứng dụng quản lý khách hàng

Cơ sở dữ liệu

Mục tiêu

Luyện tập sử dụng Eloquent, thực hiện CRUD customer cơ bản

Mô tả

Ở những bài trước chúng ta đã cấu hình CSDL, tạo dữ liệu mẫu… Ở bài hôm nay chúng ta sẽ thực hành sử dụng Eloquent để thao tác với CSDL trong ứng dụng của mình thông qua các chức năng sau:

  • Hiển thị danh sách khách hàng
  • Thêm mới khách hành
  • Cập nhật thông tin khách hành
  • Xóa khách hàng

Hướng dẫn

Bước 1: Tạo model

Tạo model Customer bằng cách chạy câu lệnh sau trên terminal:

php artisan make:model Customer

Model Customer sẽ được tạo trong thư mục app. Thêm lệnh vào file Task.php để kết nối bảng với model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
    /* The table associated with the model */
    protected $table = 'customer';
}

Bước 2: Tạo Controller

Tạo controller CustomerController bằng cách chạy câu lệnh sau trên terminal:

php artisan make:controller CustomerController

Controller Customer sẽ được tạo nằm trong thư mục app/Http/Controllers

Vào file app/Http/Controllers/CustomerController.php tạo các hàm sau

  • index() : hiển thị danh sách khách hàng
  • create(): show form tạo mới khách hàng
  • store(): thực hiện thêm mới khách hàng
  • edit(): hiển thị form và dữ liệu khách hàng cần sửa
  • update(): thực hiện tác vụ sửa
  • destroy(): xóa khách hàng

Mã nguồn tham khảo:

namespace App\Http\Controllers;
use App\Customer;
use http\Env\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class CustomerController extends Controller{

  /**
   * Display a listing of the resource.
   *
   * @return Response
   */

  public function index(){
      $customers = Customer::all();
      return view('customers.list', compact('customers'));
  }

  /**
   * Show the form for creating a new resource.
   *
   * @return Response
   */

  public function create(){
      return view('customers.create');
  }

  /**
   * Store a newly created resource in storage.
   *
   * @return Response
   */
  public function store(Request $request){
      $customer = new Customer();
      $customer->name     = $request->input('name');
      $customer->email    = $request->input('email');
      $customer->dob      = $request->input('dob');
      $customer->save();

      //dung session de dua ra thong bao
      Session::flash('success', 'Tạo mới khách hàng thành công');
      //tao moi xong quay ve trang danh sach khach hang
      return redirect()->route('customers.index');
  }

  /**
   * Show the form for editing the specified resource.
   *
   * @param  int  $id
   * @return Response
   */
  public function edit($id){
      $customer = Customer::findOrFail($id);
      return view('customers.edit', compact('customer'));
  }

  /**
   * Update the specified resource in storage.
   *
   * @param  int  $id
   * @return Response
   */
  public function update(Request $request, $id){
      $customer = Customer::findOrFail($id);
      $customer->name     = $request->input('name');
      $customer->email    = $request->input('email');
      $customer->dob      = $request->input('dob');
      $customer->save();

      //dung session de dua ra thong bao
      Session::flash('success', 'Cập nhật khách hàng thành công');
      //cap nhat xong quay ve trang danh sach khach hang
      return redirect()->route('customers.index');
  }

  /**
   * Remove the specified resource from storage.
   *
   * @param  int  $id
   * @return Response
   */
  public function destroy($id){
      $customer = Customer::findOrFail($id);
      $customer->delete();

      //dung session de dua ra thong bao
      Session::flash('success', 'Xóa khách hàng thành công');

      //xoa xong quay ve trang danh sach khach hang
      return redirect()->route('customers.index');
  }
}

Bước 3: Cấu hình route Trong thư file routes/web.php tạo các route gọi đến action tương ứng với CustomerController như sau:

use Illuminate\Support\Facades\Route;

Route::get('/', function () {
  return view('home');
});

//tao group route customers
Route::group(['prefix' => 'customers'], function () {
  Route::get('/','[email protected]')->name('customers.index');
  Route::get('/create','[email protected]')->name('customers.create');
  Route::post('/create','[email protected]')->name('customers.store');
  Route::get('/{id}/edit','[email protected]')->name('customers.edit');
  Route::post('/{id}/edit','[email protected]')->name('customers.update');
  Route::get('/{id}/destroy','[email protected]')->name('customers.destroy');
});

Bước 4: Tạo view

Tạo các view giống sở đồ sau:

resources

  • Views
    • Customers
      • list.blade.php
      • create.blade.php
      • edit.blade.php
    • home.blade.php

Nội dung home.blade.php


<!doctype html>
<html lang="en">
<head>
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
     <meta http-equiv="X-UA-Compatible" content="ie=edge">
     <title>@yield('title')</title>
     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
     <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
     <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
     <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
     @yield('content')
</div>
</body>
</html>

Nội dung view list.blade.php

@extends('home')
@section('title', 'Danh sách khách hàng')
@section('content')
     <div class="col-12">
           <div class="row">
               <div class="col-12"><h1>Danh Sách Khách Hàng</h1></div>
               <div class="col-12">
                   @if (Session::has('success'))
                      <p class="text-success">
                         <i class="fa fa-check" aria-hidden="true"></i>{{ Session::get('success') }}
                      </p>
                   @endif
               </div>
          <table class="table table-striped">
          <thead>
          <tr>
                <th scope="col">#</th>
                <th scope="col">Tên khách hàng</th>
                <th scope="col">Ngày Sinh</th>
                <th scope="col">Email</th>
                <th></th>
                <th></th>
          </tr>
          </thead>
          <tbody>
          @if(count($customers) == 0)
          <tr><td colspan="4">Không có dữ liệu</td></tr>
          @else
                @foreach($customers as $key => $customer)
                <tr>
                      <th scope="row">{{ ++$key }}</th>
                      <td>{{ $customer->name }}</td>
                      <td>{{ $customer->dob }}</td>
                      <td>{{ $customer->email }}</td>
                      <td><a href="{{ route('customers.edit', $customer->id) }}">sửa</a></td>
                      <td><a href="{{ route('customers.destroy', $customer->id) }}" class="text-danger" onclick="return confirm('Bạn chắc chắn muốn xóa?')">xóa</a></td>
                </tr>
                @endforeach
          @endif
          </tbody>
          </table>
          <a class="btn btn-primary" href="{{ route('customers.create') }}">Thêm mới</a>
          </div>
      </div>
@endsection

Nội dung view create.blade.php

@extends('home')
@section('title', 'Thêm mới khách hàng')

@section('content')
<div class="col-12 col-md-12">
   <div class="row">
      <div class="col-12">
          <h1>Thêm mới khách hàng</h1>
      </div>
      <div class="col-12">
         <form method="post" action="{{ route('customers.store') }}">
         @csrf
         <div class="form-group">
            <label>Tên khách hàng</label>
            <input type="text" class="form-control" name="name"  placeholder="Enter name" required>
         </div>
         <div class="form-group">
             <label for="exampleInputEmail1">Email</label>
             <input type="email" class="form-control" name="email" placeholder="Enter email" required>
         </div>
         <div class="form-group">
            <label for="exampleInputEmail1">Ngày sinh</label>
            <input type="date" class="form-control" name="dob" required>
         </div>
         <button type="submit" class="btn btn-primary">Submit</button>
         </form>
       </div>
     </div>
   </div>
@endsection 

Nội dung view edit.blade.php

@extends('home')
@section('title', 'Chỉnh sửa khách hàng')
@section('content')
<div class="col-12 col-md-12">
   <div class="row">
      <div class="col-12"><h1>Chỉnh sửa khách hàng</h1></div>
      <div class="col-12">
         <form method="post" action="{{ route('customers.update', $customer->id) }}">
         @csrf
         <div class="form-group">
         <label>Tên khách hàng</label>
         <input type="text" class="form-control" name="name" value="{{ $customer->name }}" required>
         </div>
         <div class="form-group">
            <label>Email</label>
            <input type="email" class="form-control" name="email" value="{{ $customer->email }}" required></div>
         <div class="form-group">
            <label>Ngày sinh</label>
            <input type="date" class="form-control" name="dob" value="{{ $customer->dob }}" required>
         </div>
         <button type="submit" class="btn btn-primary">Chỉnh sửa</button>
         <button class="btn btn-secondary" onclick="window.history.go(-1); return false;">Hủy</button>
      </form>
      </div>
     </div>
</div>
@endsection

Bước 5: Chạy ứng dụng

Sử dụng câu lệnh php artisan serve để khỏi chạy ứng dụng

Truy cập vào đường dẫn: http://localhost/customers để xem kết quả

Tổng kết

Qua bài tập này chúng ta đã ôn tập sử dụng Eloquent trong laravel

Leave a Reply

Your email address will not be published.