Laravel Setup Demo for Query Builder Eloquent

สร้างไฟล์ migration
ชื่อตารางเป็น พหูพจน์

php artisan make:migration create_phones_table

แก้ไขไฟล์ migration

Schema::create('phones', function (Blueprint $table) {
    $table->integerIncrements('id');
    $table->string('name');
    $table->string('display');
    $table->integer('weight',false,true);
});

สั่ง migrate

php artisan migrate

สร้าง model ใช้ชื่อเดียวกับตาราง แต่เป็น เอกพจน์

php artisan make:model Phone

แก้ไขไฟล์ model นิดนึง เพราะเราจะยังไม่ใช้ timestamps ตารางจะได้ดูกระชับ ดูง่าย

public $timestamps = false;

 

สร้าง controller ใช้ชื่อเดียวกับตาราง แต่เป็น เอกพจน์ ต้องมีคำว่า Controller ต่อท้าย

php artisan make:controller PhoneController

แก้ไขไฟล์  PhoneController

class PhoneController extends Controller
{
    public function index()
    {
         //Code Here
    }
}

แก้ไขไฟล์  routes\web.php

use App\Http\Controllers\PostController;

Route::get('/phones', [PhoneController::class, 'index']);

สร้างไฟล์ seeder เพื่อทำ ตัวอย่างข้อมูล
ใช้เอกพจน์ตามด้วย Seeder

php artisan make:seeder PhoneSeeder

แก้ไขไฟล์ database\seeders\PhoneSeeder.php สร้างตัวอย่างข้อมูล

use Illuminate\Support\Facades\DB;


    public function run()
    {
        DB::table('phones')->create([
            [
                'name' => 'vivo V27',
                'display' => 'AMOLED',
                'weight' => '180',
            ],
            [
                'name' => 'Redmi 12Pro',
                'display' => 'AMOLED',
                'weight' => '187',
            ],
            [
                'name' => 'Xiaomi 13Pro',
                'display' => 'AMOLED',
                'weight' => '229',
            ],
            [
                'name' => 'Huawei P60',
                'display' => 'OLED',
                'weight' => '206',
            ],
            [
                'name' => 'Apple iPhone 14Pro',
                'display' => 'AMOLED',
                'weight' => '204',
            ],
            [
                'name' => 'ASUS ROG Phone6',
                'display' => 'AMOLED',
                'weight' => '239',
            ]
        ]);
    }

สั่งรัน seeder เอาข้อมูลเข้าฐานข้อมูล

php artisan db:seed --class=PhoneSeeder

ตารางข้อมูลที่ใช้เป็นตัวอย่าง

id        name                display     weight
1         vivo V27            AMOLED      180
2         Redmi 12Pro         AMOLED      187
3         Xiaomi 13Pro        AMOLED      229
4         Huawei P60          OLED        206
5         Apple iPhone14      AMOLED      204
6         ASUS ROG Phone6     AMOLED      239
Exit mobile version