[Thực hành] Sử dụng Eloquent trong ứng dụng Task Management

Cơ sở dữ liệu

Mục tiêu

Luyện tập sử dụng Eloquent, thực hiện CRUD task 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 task
  • Thêm mới một task
  • Cập nhật thông tin task
  • Xóa một task

Hướng dẫn

Bước 1: Tạo model

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

php artisan make:model Task

Model Task 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 Task extends Model
{
    /* The table associated with the model. */
    protected $table = 'task';
}

Bước 2: Tạo Controller

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

php artisan make:controller TaskController

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

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

  • index() : hiển thị danh sách task
  • create(): show form tạo mới task
  • store(): thực hiện thêm mới task
  • edit(): hiển thị form và dữ liệu task cần sửa
  • update(): thực hiện tác vụ sửa
  • destroy(): xóa task
<?php
namespace App\Http\Controllers;
use App\Task;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use http\Env\Response;
use Illuminate\Support\Facades\Storage;


class TaskController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return Response
   */

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

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

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

  /**
   * Store a newly created resource in storage.
   *
   * @return Response
   */

  public function store(Request $request)
  {
      $task = new Task();
      $task->title = $request->input('title');
      $task->content = $request->input('content');

      //upload file
      if ($request->hasFile('image')) {
          $image = $request->file('image');
          $path = $image->store('images', 'public');
          $task->image = $path;
      }

      $task->due_date = $request->input('due_date');
      $task->save();

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

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

  /**
   * Update the specified resource in storage.
   *
   * @param  int  $id
   * @return Response
   */
  public function update(Request $request, $id)
  {
      $task = Task::findOrFail($id);
      $task->title = $request->input('title');
      $task->content = $request->input('content');

      //cap nhat anh
      if ($request->hasFile('image')) {

          //xoa anh cu neu co
          $currentImg = $task->image;
          if ($currentImg) {
              Storage::delete('/public/' . $currentImg);
          }
          // cap nhat anh moi
          $image = $request->file('image');
          $path = $image->store('images', 'public');
          $task->image = $path;
      }

      $task->due_date = $request->input('due_date');
      $task->save();

      //dung session de dua ra thong bao
      Session::flash('success', 'Cập nhật thành công');
      //tao moi xong quay ve trang danh sach task
      return redirect()->route('tasks.index');
  }

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

      //delete image
      if ($image) {
          Storage::delete('/public/' . $image);
      }

      $task->delete();

      //dung session de dua ra thong bao
      Session::flash('success', 'Xóa thành công');
      //xoa xong quay ve trang danh sach task
      return redirect()->route('tasks.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 TaskController như sau:

use Illuminate\Support\Facades\Route;

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

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

Bước 4: Tạo view

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

resources

  • Views
    • tasks
      • 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">

</head>

<body>

<div class="container">

  @yield('content')

</div>

</body>

<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>

</html>

Nội dung view create.blade.php

@extends('home')

@section('title', 'Thêm mới công viêc')

@section('content')

  <div class="row">

      <div class="col-md-12">

          <h2>Thêm mới công việc</h2>

      </div>

      <div class="col-md-12">

          <form method="post" action="{{ route('tasks.store') }}" enctype="multipart/form-data">

              @csrf

              <div class="form-group">

                  <label >Tên công việc</label>

                  <input type="text" class="form-control" name="title" required>

              </div>

              <div class="form-group">

                  <label >Nội dung</label>

                  <textarea class="form-control" rows="3" name="content" required></textarea>

              </div>

              <div class="form-group">

                  <label for="exampleFormControlFile1">Ảnh</label>

                  <input type="file" name="image" class="form-control-file" required>

              </div>

              <div class="form-group">

                  <label for="exampleFormControlFile1">Ngày hết hạn</label>

                  <input type="date" name="due_date" class="form-control" required>

              </div>

              <button type="submit" class="btn btn-primary">Thêm mới</button>

              <button class="btn btn-secondary" onclick="window.history.go(-1); return false;">Hủy</button>

          </form>

      </div>

  </div>

@endsection

Nội dung view edit.blade.php

@extends('home')

@section('title', 'Cập nhật công viêc')

@section('content')

  <div class="row">

      <div class="col-md-12">

          <h2>Cập nhật công việc</h2>

      </div>

      <div class="col-md-12">

          <form method="post" action="{{ route('tasks.update', $task->id) }}" enctype="multipart/form-data">

              @csrf

              <div class="form-group">

                  <label>Tên công việc</label>

                  <input type="text" class="form-control" name="title" value="{{ $task->title }}" required>

              </div>

              <div class="form-group">

                  <label>Nội dung</label>

                  <textarea class="form-control" rows="3" name="content"  required>{{ $task->content }}</textarea>

              </div>

              <div class="form-group">

                  <label>Ảnh</label>

                  <input type="file" name="image" class="form-control-file" >

              </div>

              <div class="form-group">

                  <label>Ngày hết hạn</label>

                  <input type="date" name="due_date" class="form-control"  value="{{ $task->due_date }}" 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>

@endsection

Bước 5: Tạo liên kết tượng trưng đến thư mục public disk

The public disk  dành cho các tệp tin sẽ được truy cập công khai. Theo mặc định, the public disk sử dụng trình điều khiển cục bộ và lưu trữ các tệp này trong storage/app/public. Để giúp họ có thể truy cập được từ web, bạn nên tạo liên kết biểu tượng từ public/storage sang storage/app/public. Quy ước này sẽ giữ các tập tin truy cập công cộng của bạn trong một thư mục có thể dễ dàng chia sẻ qua các triển khai khi sử dụng các hệ thống triển khai không xuống thời gian như Envoyer

Để tạo liên kết tượng trưng, sử dụng storage:link Artisan command:

php artisan storage:link 

Bước 6: 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/tasks để 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.