Bài 2: Hướng dẫn tìm hiểu kiến trúc MVC trong Laravel Framework

Hướng dẫn tìm hiểu kiến trúc MVC trong Laravel Framework

Nội dung 1: Demo luồng hoạt động MVC

1. Tạo Route (gioi-thieu) Mở file routes/web.php và khai báo:

<?php
use App\Http\Controllers\HomeController; // import lớp controller
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
});

// Route mới
Route::get('gioi-thieu', [HomeController::class, 'about']);

2. Tạo HomeController

<?php
namespace App\Http\Controllers;

class HomeController extends Controller
{
    public function about()
    {
        // Trả về view 'about.blade.php' trong thư mục resources/views
        return view('about');
    }
}

3. Tạo view about.blade.php

<!DOCTYPE html>
<html lang="">
<head>
    <meta charset="utf-8">
    <title>Giới thiệu</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <h1 class="text-center">Hello About</h1> 
</body>
</html>

4. Khởi động server và truy cập

php artisan serve

Mở trình duyệt: http://localhost:8000/gioi-thieu


Nội dung 2: Giới thiệu Blade View

1. Khác biệt giữa Blade view và PHP view

2. Cú pháp thường gặp

{{ $variable }}         {{-- Hiển thị biến --}}
{!! $html !!}           {{-- Hiển thị HTML --}}
@if(condition) ... @endif
@foreach($list as $item) ... @endforeach

3. Truyền dữ liệu từ Controller qua Blade

return view('about', ['name' => 'Laravel']);
<p>Xin chào {{ $name }}</p>

4. Master View

<!DOCTYPE html>
<html>
<head>
    <title>@yield('title')</title>
</head>
<body>
    <header>Menu...</header>
    <main>
        @yield('content')
    </main>
</body>
</html>
@extends('layouts.master')

@section('title', 'Trang giới thiệu')

@section('content')
    <h1>Giới thiệu Laravel</h1>
@endsection

Nội dung 3: Kết nối CSDL và CRUD cơ bản

1. Cấu hình kết nối trong .env

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

2. Tạo model & migration cho bảng categories

php artisan make:model Category -m

Trong file migration (database/migrations/...create_categories_table.php):

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });

    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('categories');
    }
};

Chạy lệnh:

php artisan migrate

3. Tạo controller CRUD

php artisan make:controller CategoryController

4. Khai báo Route CRUD

Route::resource('categories', CategoryController::class);

5. Tạo các view cho CRUD

Trong thư mục resources/views/category, ta sẽ tạo các file view sau:


a) index.blade.php – Danh sách Category

@extends('layout.master') 

@section('title', 'Danh sách Category')

@section('content')
<div class="container">
    <h2>Danh sách Category</h2>
    <a href="{{ route('category.create') }}" class="btn btn-success">Thêm mới</a>
    <table class="table table-bordered mt-3">
        <tr>
            <th>ID</th>
            <th>Tên Category</th>
            <th>Hành động</th>
        </tr>
        @foreach ($categories as $cat)
        <tr>
            <td>{{ $cat->id }}</td>
            <td>{{ $cat->name }}</td>
            <td>
                <a href="{{ route('category.edit', $cat->id) }}" class="btn btn-warning">Sửa</a>
                <form action="{{ route('category.destroy', $cat->id) }}" method="POST" style="display:inline;">
                    @csrf
                    @method('DELETE')
                    <button onclick="return confirm('Xóa?')" class="btn btn-danger">Xóa</button>
                </form>
            </td>
        </tr>
        @endforeach
    </table>
</div>
@endsection

b) create.blade.php – Form thêm mới

@extends('layout.master')

@section('title', 'Thêm Category')

@section('content')
<div class="container">
    <h2>Thêm Category</h2>
    <form action="{{ route('category.store') }}" method="POST">
        @csrf
        <div class="form-group">
            <label>Tên Category</label>
            <input type="text" name="name" class="form-control" required>
        </div>
        <button class="btn btn-primary">Lưu</button>
    </form>
</div>
@endsection

c) edit.blade.php – Form chỉnh sửa

@extends('layout.master')

@section('title', 'Sửa Category')

@section('content')
<div class="container">
    <h2>Sửa Category</h2>
    <form action="{{ route('category.update', $category->id) }}" method="POST">
        @csrf
        @method('PUT')
        <div class="form-group">
            <label>Tên Category</label>
            <input type="text" name="name" value="{{ $category->name }}" class="form-control" required>
        </div>
        <button class="btn btn-primary">Cập nhật</button>
    </form>
</div>
@endsection

d) layout/master.blade.php – Master layout

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>@yield('title')</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
    @yield('content')
</body>
</html>