Skip to content

Views

Giới thiệu (Introduction)

Việc trả toàn bộ HTML document strings trực tiếp từ routes/controllers không thực tế. Views cung cấp cách thuận tiện để đặt HTML trong các files riêng biệt.

Views tách biệt logic controller/application khỏi logic presentation và được lưu trong thư mục resources/views. View templates thường viết bằng Blade templating language:

html
<!-- View lưu tại resources/views/greeting.blade.php -->

<html>
    <body>
        <h1>Hello, {{ $name }}</h1>
    </body>
</html>

Trả view từ route:

php
Route::get('/', function () {
    return view('greeting', ['name' => 'James']);
});

Viết Views trong React / Svelte / Vue

Thay vì viết frontend templates bằng Blade, bạn có thể viết bằng React, Svelte hoặc Vue thông qua Inertia. Inertia đơn giản hóa việc kết nối Laravel backend với frontend SPA mà không cần API riêng.

Sử dụng starter kits để nhanh chóng scaffold ứng dụng Laravel + Inertia.

Tạo và Render Views (Creating and Rendering Views)

Tạo view bằng cách đặt file .blade.php trong resources/views hoặc dùng lệnh Artisan:

bash
php artisan make:view greeting

Trả view từ route/controller bằng view helper:

php
Route::get('/', function () {
    return view('greeting', ['name' => 'James']);
});

Hoặc dùng View facade:

php
use Illuminate\Support\Facades\View;

return View::make('greeting', ['name' => 'James']);

Nested View Directories (Thư mục lồng nhau)

Views có thể nằm trong subdirectories, dùng "dot" notation:

php
// resources/views/admin/profile.blade.php
return view('admin.profile', $data);

Tạo View đầu tiên khả dụng

php
return view()->first(['custom.admin', 'admin'], $data);

Kiểm tra View có tồn tại

php
use Illuminate\Support\Facades\View;

if (View::exists('admin.profile')) {
    // ...
}

Truyền Data cho Views (Passing Data to Views)

Truyền array data:

php
return view('greetings', ['name' => 'Victoria']);

Dùng method with:

php
return view('greeting')
    ->with('name', 'Victoria')
    ->with('occupation', 'Astronaut');

Chia sẻ Data với tất cả Views

Dùng View::share trong method boot của service provider:

php
<?php

namespace App\Providers;

use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        View::share('key', 'value');
    }
}

View Composers

View composers là callbacks hoặc class methods được gọi khi view render. Nếu bạn có data cần bind vào view mỗi khi render, view composer giúp tổ chức logic vào một nơi.

Đăng ký view composers trong service providers:

php
<?php

namespace App\Providers;

use App\View\Composers\ProfileComposer;
use Illuminate\Support\Facades;
use Illuminate\Support\ServiceProvider;
use Illuminate\View\View;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        // Class-based composers
        Facades\View::composer('profile', ProfileComposer::class);

        // Closure-based composers
        Facades\View::composer('welcome', function (View $view) {
            // ...
        });
    }
}

Ví dụ class-based composer:

php
<?php

namespace App\View\Composers;

use App\Repositories\UserRepository;
use Illuminate\View\View;

class ProfileComposer
{
    public function __construct(
        protected UserRepository $users,
    ) {}

    /**
     * Bind data vào view.
     */
    public function compose(View $view): void
    {
        $view->with('count', $this->users->count());
    }
}

Gắn Composer cho nhiều Views

php
use Illuminate\Support\Facades\View;

View::composer(
    ['profile', 'dashboard'],
    MultiComposer::class,
);

// Tất cả views
View::composer('*', function (View $view) {
    // ...
});

View Creators

View creators tương tự composers nhưng được gọi ngay khi view được khởi tạo (instantiated) thay vì khi sắp render:

php
use App\View\Creators\ProfileCreator;
use Illuminate\Support\Facades\View;

View::creator('profile', ProfileCreator::class);

Tối ưu Views (Optimizing Views)

Mặc định, Blade template views được biên dịch theo yêu cầu (on demand). Khi deploy, pre-compile tất cả views:

bash
php artisan view:cache

Xóa view cache:

bash
php artisan view:clear