1.首先先創建專案 並設定好資料庫.env及相關設定app.php
於.env設定連接資料庫(創建schema) ,app.php設定timezone
composer create-project --prefer-dist laravel/laravel APIserver
'timezone' => 'Asia/Taipei',
1.創建Product Model及controller
php artisan make:controller ProductController --resource //創建有CRUD
2.建立model
php artisan make:model Product //創建model
3.建立Product migration ,創建後新增table欄位title,content,price,quantity
設定table後執行migrate,創建資料庫的table
php artisan make:migration create_products
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('content');
$table->integer('price');
$table->integer('quantity');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('products');
}
4.設定一些假資料(seeder),建立一個屬於Product seeder
php artisan make:seeder ProductSeeder
public function run()
{
Product::create(['title' =>'測試產品01' , 'content' => '測試產品描述' , 'price' => rand(0,300) , 'quantity' => 20]);
Product::create(['title' =>'測試產品02' , 'content' => '測試產品描述' , 'price' => rand(0,300) , 'quantity' => 20]);
Product::upsert([
['id' =>'3' ,'title' =>'固定產品03' , 'content' => '固定產品描述' , 'price' => rand(0,300) , 'quantity' => 10],
['id' =>'4' ,'title' =>'固定產品04' , 'content' => '固定產品描述' , 'price' => rand(0,300) , 'quantity' => 10]
], ['id'],['price' ,'quantity']);
}