Bài 4: Các lệnh artisan tạo Model, Controller và Migration trong laravel Framework

1. Các lệnh artisan tạo Model, Controller và Migration trong laravel Framework

Phần 1: Lý thuyết đọc hiểu

Trong Laravel Framework, bạn có thể dùng Artisan Command để nhanh chóng tạo ra Model, ControllerMigration mà không cần viết thủ công từng file.

Điều này giúp tiết kiệm thời gian và đảm bảo cấu trúc tuân theo chuẩn của Laravel.


1. Tạo Model

Cú pháp:

php artisan make:model TênModel

Ví dụ:

php artisan make:model Product

Kết quả:

Tùy chọn mở rộng:

Ví dụ đầy đủ:

php artisan make:model Product -mcrfs

=> Tạo Model Product, Migration, Controller resource, Factory, Seeder.


2. Tạo Controller

Cú pháp:

php artisan make:controller TênController

Ví dụ:

php artisan make:controller ProductController

Kết quả:

Tùy chọn:

Ví dụ:

php artisan make:controller ProductController -r --model=Product

=> Tạo controller resource, tự động import App\Models\Product.


3. Tạo Migration

Cú pháp:

php artisan make:migration tên_bảng

Ví dụ:

php artisan make:migration create_products_table

Kết quả:

Một số tùy chọn:

Ví dụ:

php artisan make:migration add_price_to_products_table --table=products

=> Migration thêm cột price vào bảng products.


4. Kết hợp tạo Model + Controller + Migration

Laravel cho phép bạn gộp trong một lệnh duy nhất:

php artisan make:model Product -mcr

5. Chạy Migration

Sau khi tạo migration, chạy:

php artisan migrate

=> Laravel sẽ tạo hoặc cập nhật bảng trong database.


Tóm lại:


Hình ảnh minh họa trực quan luồng tạo và liên kết Model – Controller – Migration trong Laravel

Phần 2. Các lệnh thường dùng nhất trong kháo học

1. Lệnh tạo model + migration

php artisan make:model Product -m
  1. Tạo resource Controller (Cần chỉ định rõ model)
php artisan make:controller ProductController --model=Product

2. Lệnh migrate

Mở cmd và chạy lệnh

php artisan migrate
  • Lệnh trên sẽ tìm và áp dụng tất cả các file migratiion trong thư mục database\migrations và tạo cấu trúc các bảng theo thông tin khai báo trong các file đó
  • Nó sẽ chạy hàm up trong file migration
 /**
 * Run the migrations.
 */
public function up(): void
{
    Schema::create('categories', function (Blueprint $table) {
        $table->id(); // id bigint unsigned primary key auto_increment
        $table->string('name'); //name varchar(255) NOT NULL
        $table->tinyInteger('status')->nullable()->default(1); /// status tinyint null default(1)
        $table->timestamps(); // created_at, updated_at
    });
}

3. Lệnh migrate:rollback

php artisan migrate:rollback

Lệnh trên sẽ hủy bỏ áp dụng của lệnh migration gần nhất

Nó sẽ thực thì hàm down trong file migration

/**
 * Reverse the migrations.
 */
public function down(): void
{
    Schema::dropIfExists('products');
}

2. Lệnh migrate:refresh

php artisan migrate:refresh

Lệnh trên sẽ chạy lần lượt 2 lệnh migrate và rollback, nghĩa là nó xóa migration rồi áp dụng lại

Phần 3. Bài tập thực hành tạo model, migration và controller

Lưu ý quan trọng: Trước khi thực hành, hãy tạo một databaase trong phpmyadmin VD `ql_ban_hang

Sau đó tìm và mở file .env tại thưc mục gốc của dự án và tiến hành cấu hình kết nới tới cơ sở dữ liệu ql_ban_hang vừa tạo ở trên

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

Sau đó tiến hành các bước dưới đây

Bước 1: Tạo Model + Migration

Mở cmd trong thư mục dự án và chạy lệnh Lện tạo model + migration Category

php artisan make::model Category -m

Lện tạo Controller resource

Lệnh này cần chỉ rõ tên model như dưới đây

php artisan make:controller ProductController --model=Product

2 lệnh trên sẽ tạo lần lượt các file

2 Model trong thư mục App\Models

2 migration trong thư mục database\migrations

Bước 2: Khai báo cấu trúc bảng trong các file Migration

1. Tìm mở file database\migrations\2025_08_13_081437_create_products_table.php và khai báo như sau:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id(); // id bigint unsigned primary key auto_increment
            $table->string('name'); //name varchar(255) NOT NULL
            $table->tinyInteger('status')->nullable()->default(1); /// status tinyint null default(1)
            $table->timestamps(); // created_at, updated_at
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('categories');
    }
};

2. Tìm mở file database\migrations\2025_08_13_081437_create_products_table.php và khai báo như sau:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name', 100)->unique(); //name varchar(100) NOT NULL
            $table->float('price', 10,2); //price float(10,2)
            $table->string('image'); //image varchar(255) NOT NULL
            $table->tinyInteger('status')->nullable()->default(1); /// status tinyint null default(1)
            $table->unsignedBigInteger('category_id'); // Foreign key column
            $table->foreign('category_id')->references('id')->on('categories');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('products');
    }
};

Bước 3. Lệnh áp dụng migrate để tạo bảng đã khai báo ở trên

1. Lệnh migrate

Mở cmd và chạy lệnh

php artisan migrate

Lệnh trên sẽ tìm và áp dụng tất cả các file migratiion trong thư mục database\migrations và tạo cấu trúc các bảng theo thông tin khai báo trong các file đó

Nó sẽ chạy hàm up trong file migration

Kiểm tra lại database để xem cấu trúc các bảng đã được tạo

 /**
 * Run the migrations.
 */
public function up(): void
{
    Schema::create('categories', function (Blueprint $table) {
        $table->id(); // id bigint unsigned primary key auto_increment
        $table->string('name'); //name varchar(255) NOT NULL
        $table->tinyInteger('status')->nullable()->default(1); /// status tinyint null default(1)
        $table->timestamps(); // created_at, updated_at
    });
}

2. Lệnh migrate:rollback

php artisan migrate:rollback
  • Lệnh trên sẽ hủy bỏ áp dụng của lệnh migration gần nhất
  • Nó sẽ thực thì hàm down trong file migration
/**
 * Reverse the migrations.
 */
public function down(): void
{
    Schema::dropIfExists('products');
}

2. Lệnh migrate:refresh

php artisan migrate:refresh

Lệnh trên sẽ chạy lần lượt 2 lệnh migrate và rollback, nghĩa là nó xóa migration rồi áp dụng lại