Bài 5: Hướng dẫn từng bước thực hành chức năng thêm, sửa, xóa (CRUD) trong laravel

Hướng dẫn từng bước thực hành chức năng thêm, sửa, xóa (CRUD) trong laravel

Dưới đây là hướng dẫn thêm – sửa – xóa trong Laravel với ví dụ cụ thể, từng bước từ đầu đến cuối. Mình sẽ dùng ví dụ quản lý danh mục (categories) với MySQL.

lưu ý quan trọng: Hãy tạo CSDL rỗng đặt tên là ql_ban_hang và cấu hình kết nối CSDL này trong file .env tại thư mục gốc của dự án laravel

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE= ql_ban_hang
DB_USERNAME=root
DB_PASSWORD=

1. Tạo migration và model

Nếu bạn đã có model category rồi thì bỏ qua bước này

php artisan make:model Category -m

database/migrations/xxxx_create_categories_table.php

public function up(): void
{
    Schema::create('categories', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->boolean('status')->default(1); // 1: active, 0: inactive
        $table->timestamps();
    });
}
php artisan migrate

app/Models/Category.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $fillable = ['name', 'status'];
}

2. Tạo Controller

php artisan make:controller CategoryController --resource

app/Http/Controllers/CategoryController.php

namespace App\Http\Controllers;

use App\Models\Category;
use Illuminate\Http\Request;

class CategoryController extends Controller
{
    public function index()
    {
        $categories = Category::all();
        return view('categories.index', compact('categories'));
    }

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

    public function store(Request $request)
    {
        $request->validate([
            'name'   => 'required|string|max:255|unique:categories',
            'status' => 'required|boolean',
        ]);

        Category::create($request->only('name', 'status'));

        return redirect()->route('categories.index')->with('success', 'Thêm danh mục thành công!');
    }

    public function edit(Category $category)
    {
        return view('categories.edit', compact('category'));
    }

    public function update(Request $request, Category $category)
    {
        $request->validate([
            'name'   => 'required|string|max:255|unique:categories,name,'.$category->id,
            'status' => 'required|boolean',
        ]);

        $category->update($request->only('name', 'status'));

        return redirect()->route('categories.index')->with('success', 'Cập nhật thành công!');
    }

    public function destroy(Category $category)
    {
        $category->delete();
        return redirect()->route('categories.index')->with('success', 'Xóa thành công!');
    }
}

3. Khai báo Route

routes/web.php

use App\Http\Controllers\CategoryController;

Route::resource('categories', CategoryController::class);

4. Tạo View

resources/views/categories/index.blade.php

<h1>Danh sách danh mục</h1>
<a href="{{ route('categories.create') }}">Thêm mới</a>

@if(session('success'))
    <p style="color: green">{{ session('success') }}</p>
@endif

<table border="1" cellpadding="5">
    <tr>
        <th>ID</th>
        <th>Tên</th>
        <th>Trạng thái</th>
        <th>Ngày tạo</th>
        <th>Ngày cập nhật</th>
        <th>Hành động</th>
    </tr>
    @foreach($categories as $cat)
    <tr>
        <td>{{ $cat->id }}</td>
        <td>{{ $cat->name }}</td>
        <td>{{ $cat->status ? 'Hoạt động' : 'Ngừng' }}</td>
        <td>{{ $cat->created_at }}</td>
        <td>{{ $cat->updated_at }}</td>
        <td>
            <a href="{{ route('categories.edit', $cat) }}">Sửa</a>
            <form action="{{ route('categories.destroy', $cat) }}" method="POST" style="display:inline">
                @csrf
                @method('DELETE')
                <button type="submit" onclick="return confirm('Xóa danh mục này?')">Xóa</button>
            </form>
        </td>
    </tr>
    @endforeach
</table>

resources/views/categories/create.blade.php

<h1>Thêm danh mục</h1>
<form action="{{ route('categories.store') }}" method="POST">
    @csrf
    Tên: <input type="text" name="name"><br>
    Trạng thái:
    <select name="status">
        <option value="1">Hoạt động</option>
        <option value="0">Ngừng</option>
    </select><br>
    <button type="submit">Lưu</button>
</form>
<a href="{{ route('categories.index') }}">Quay lại</a>

resources/views/categories/edit.blade.php

<h1>Sửa danh mục</h1>
<form action="{{ route('categories.update', $category) }}" method="POST">
    @csrf
    @method('PUT')
    Tên: <input type="text" name="name" value="{{ $category->name }}"><br>
    Trạng thái:
    <select name="status">
        <option value="1" {{ $category->status ? 'selected' : '' }}>Hoạt động</option>
        <option value="0" {{ !$category->status ? 'selected' : '' }}>Ngừng</option>
    </select><br>
    <button type="submit">Cập nhật</button>
</form>
<a href="{{ route('categories.index') }}">Quay lại</a>

5. Chạy thử

php artisan serve

Mở: http://127.0.0.1:8000/categories → Thêm, sửa, xóa danh mục.


📄 ĐỀ BÀI ÔN TẬP LARAVEL – CRUD PRODUCTS

Mục tiêu: Sinh viên thực hành tạo ứng dụng Laravel quản lý sản phẩm, áp dụng kiến thức về migration, model, controller, route, view, và form validation.


1. Yêu cầu cơ sở dữ liệu

Tạo bảng products với các trường sau:

Tên cột Kiểu dữ liệu Ghi chú
id BIGINT (PK, AI) Khóa chính, tự tăng
name VARCHAR(255) Tên sản phẩm
price DECIMAL(10,2) Giá sản phẩm
status BOOLEAN 1: Còn hàng, 0: Hết hàng
created_at TIMESTAMP Tự sinh bởi Laravel
updated_at TIMESTAMP Tự sinh bởi Laravel

2. Yêu cầu chức năng

Sinh viên phải thực hiện đầy đủ các chức năng sau:

  1. Xem danh sách sản phẩm

    • Hiển thị bảng gồm ID, tên, giá, trạng thái, ngày tạo, ngày cập nhật.
    • Có nút Thêm mớiSửa / Xóa từng sản phẩm.
  2. Thêm sản phẩm mới

    • Form nhập gồm: Tên, Giá, Trạng thái (dropdown chọn "Còn hàng" hoặc "Hết hàng").

    • Có kiểm tra dữ liệu:

      • name: bắt buộc, tối đa 255 ký tự.
      • price: bắt buộc, số, lớn hơn hoặc bằng 0.
      • status: bắt buộc, chỉ nhận 0 hoặc 1.
    • Sau khi thêm thành công quay về danh sách và hiển thị thông báo.

  3. Sửa thông tin sản phẩm

    • Lấy dữ liệu từ DB đổ vào form để chỉnh sửa.
    • Có validate tương tự khi thêm mới.
    • Lưu cập nhật và quay về danh sách.
  4. Xóa sản phẩm

    • Xóa cứng (khỏi DB).
    • Có hộp thoại xác nhận trước khi xóa.

3. Kỹ thuật bắt buộc