I. Kết nối Database
1. Tạo Database trên XAMPP
- chỉ tạo database chứ không tạo bảng hay cột gì hết
2. Kết nối Laravel với Database
- Sửa file /.env như sau:
1 2 3 4 5 6 |
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=demolaravel //tên database vừa tạo bên trên DB_USERNAME=root DB_PASSWORD= |
II. Tạo các bảng, cột thông qua Migrate
1. Tạo bảng bằng Migrate
- Tạo 3 bảng Database: Category, Brand, Product bằng Terminal
1 2 3 4 5 |
php artisan make:migration create_category --create=category php artisan make:migration create_brand --create=brand php artisan make:migration create_product --create=product //create_category: là tạo class CreateCategory //create=category: là tạo bảng tên category |
- Vào database/migrations/... thấy có 3 bảng vừa tạo
2. Tạo cột với mỗi bảng
- Với bảng Product ta có thể tạo như sau (2 bảng còn lại tương tự)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateProduct extends Migration { public function up() { Schema::create('product', function (Blueprint $table) { $table->bigIncrements('id'); //PK + unsigned big interger + auto increment $table->string('product_name',191)->unique(); //varchar(191) $table->string('product_desc')->nullable(); //varchar(255) $table->string('thumbnail')->nullable(); $table->string('gallery')->nullable(); $table->unsignedBigInteger('category_id'); $table->unsignedBigInteger('brand_id'); $table->decimal('price',12,4); // tiền $ là 12,4. VNĐ là 16,0 $table->unsignedInteger('quantity')->default(1); $table->timestamps(); //tạo 1 lúc 2 columns: created_ad update_ad //khóa ngoài $table->foreign('category_id')->references('id')->on('category'); $table->foreign('brand_id')->references('id')->on('brand'); }); } public function down() { Schema::dropIfExists('product'); } } |
3. Khởi chạy Migrate
- Dùng terminal
1 |
php artisan migrate |
- Quay lại database, thấy 3 bảng đã được tạo với các cột như trên