Học Laravel 10 cơ bản – Bài 5: Database & Eloquent ORM trong Laravel 10

Học Laravel 10 cơ bản – Bài 5: Database & Eloquent ORM trong Laravel 10

Trong bài này, chúng ta sẽ tìm hiểu Database Eloquent ORM Laravel 10 để quản lý cơ sở dữ liệu, tạo Model và thao tác CRUD. Đây là phần quan trọng giúp bạn làm việc với dữ liệu trong ứng dụng Laravel.


1. Cấu hình Database

Trong file .env, sửa thông tin kết nối:

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

👉 Chạy lệnh test kết nối:

php artisan migrate

Nếu OK → Laravel tạo sẵn các bảng users, password_resets, failed_jobs


2. Migration (Tạo bảng)

Migration giúp quản lý schema DB bằng code.

Tạo migration:

php artisan make:migration create_posts_table

File: database/migrations/xxxx_create_posts_table.php

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

return new class extends Migration { 
     public function up(): void { 
            Schema::create('posts', function (Blueprint $table) { 
                $table->id(); $table->string('title'); 
                $table->text('content')->nullable(); 
                $table->timestamps(); 
            }); 
      } 

      public function down(): void { 
            Schema::dropIfExists('posts'); 
      } 
};

Chạy migration:

php artisan migrate

👉 DB có bảng posts.


3. Seeder & Factory (Tạo dữ liệu mẫu)

Tạo seeder:

php artisan make:seeder PostSeeder

File database/seeders/PostSeeder.php:

namespace Database\Seeders; 
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB; 

class PostSeeder extends Seeder { 
   public function run(): void { 
       DB::table('posts')->insert([ 
             'title' => 'Bài viết đầu tiên', 
             'content' => 'Nội dung chi tiết...', 
             'created_at' => now(), 'updated_at' => now(), 
       ]); 
   } 
}

Chạy seeder:

php artisan db:seed --class=PostSeeder

4. Model (ORM – Eloquent)

Tạo Model:

php artisan make:model Post

File: app/Models/Post.php

namespace App\Models; 
use Illuminate\Database\Eloquent\Factories\HasFactory; 
use Illuminate\Database\Eloquent\Model; 

class Post extends Model { 
      use HasFactory; 
      protected $fillable = ['title', 'content']; 
}

5. CRUD với Eloquent

Tạo dữ liệu:

$post = Post::create([ 
     'title' => 'Laravel 10 ORM', 
     'content' => 'Giới thiệu Eloquent ORM trong Laravel 10', 
]);

Lấy dữ liệu:

$all = Post::all(); // Lấy tất cả 
$find = Post::find(1); // Tìm theo ID 
$where = Post::where('title', 'like', '%Laravel%')->get();

Cập nhật:

$post = Post::find(1); 
$post->title = "Tiêu đề mới"; 
$post->save();

Xóa:

$post = Post::find(1); 
$post->delete();

6. Quan hệ (Relationship)

One-to-One

Ví dụ: 1 User có 1 Profile.

User.php

public function profile() { 
    return $this->hasOne(Profile::class); 
}

Profile.php

public function user() { 
    return $this->belongsTo(User::class); 
}

Dùng:

$user = User::find(1); 
$profile = $user->profile;

One-to-Many

Ví dụ: 1 User có nhiều Post.

User.php

public function posts() { 
    return $this->hasMany(Post::class); 
}

Post.php

public function user() { 
    return $this->belongsTo(User::class); 
}

Dùng:

$user = User::find(1); 

foreach ($user->posts as $post) { 
    echo $post->title; 
}

Many-to-Many

Ví dụ: Post có nhiều Tag, Tag thuộc nhiều Post.

Post.php

public function tags() { 
    return $this->belongsToMany(Tag::class); 
}

Tag.php

public function posts() { 
    return $this->belongsToMany(Post::class); 
}

👉 Laravel mặc định dùng bảng trung gian post_tag.


7. Query Builder vs Eloquent

  • Query Builder: viết query SQL ngắn gọn.

DB::table('posts')->where('id', 1)->first();

  • Eloquent: dùng model.

Post::find(1);

✅ Kết luận

Trong bài này bạn đã học:

  • Cấu hình database.

  • Migration để quản lý schema.

  • Seeder & Factory để tạo dữ liệu mẫu.

  • Model & CRUD với Eloquent ORM.

  • Các quan hệ trong Eloquent: One-to-One, One-to-Many, Many-to-Many.