📖 Laravel Cơ bản đến Nâng cao - Eloquent ORM và Database
90 phút

Eloquent ORM và Database

Migrations

Tạo Migration

php artisan make:migration create_users_table

File Migration mẫu

<?php

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

return new class extends Migration
{
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

Chạy Migration

php artisan migrate

Eloquent Models

Tạo Model

php artisan make:model User

Model cơ bản

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $fillable = ['name', 'email', 'password'];
    
    protected $hidden = ['password', 'remember_token'];
}

CRUD với Eloquent

Tạo bản ghi

$user = new User();
$user->name = 'John Doe';
$user->email = 'john@example.com';
$user->password = bcrypt('password');
$user->save();

// Hoặc sử dụng create
User::create([
    'name' => 'Jane Doe',
    'email' => 'jane@example.com',
    'password' => bcrypt('password')
]);

Đọc dữ liệu

// Lấy tất cả users
$users = User::all();

// Lấy user theo ID
$user = User::find(1);

// Điều kiện tìm kiếm
$users = User::where('active', 1)
             ->orderBy('name')
             ->take(10)
             ->get();

Cập nhật

$user = User::find(1);
$user->name = 'New Name';
$user->save();

// Hoặc update trực tiếp
User::where('active', 1)
    ->update(['active' => 0]);

Xóa

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

// Xóa trực tiếp
User::destroy(1);
User::where('active', 0)->delete();

Relationships

One to Many

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

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

Sử dụng Relationship

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

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

Bài tập tiếp theo

Chúng ta sẽ học về Blade Templates và Forms!

📝 Bài tập (1)

  1. Thực hành tạo model Post với migration

Bài học "Eloquent ORM và Database" - Khóa học "Laravel Cơ bản đến Nâng cao"