> ## Documentation Index
> Fetch the complete documentation index at: https://inertiajs-vi.tuantq.online/llms.txt
> Use this file to discover all available pages before exploring further.

# Response

<Warning>Bạn đang xem tài liệu Inertia.js v2. Inertia.js v3 đã được phát hành và hiện là phiên bản mặc định. Hãy xem [hướng dẫn nâng cấp](/v3/getting-started/upgrade-guide) để bắt đầu.</Warning>

## Tạo response

Tạo response Inertia rất đơn giản. Hãy gọi phương thức `Inertia::render()` trong controller hoặc route, truyền tên [page component JavaScript](/v2/the-basics/pages) cần render cùng các property (dữ liệu) dành cho trang.

Trong ví dụ bên dưới, chúng ta truyền một property duy nhất (`event`) chứa bốn attribute (`id`, `title`, `start_date` và `description`) cho page component `Event/Show`.

```php theme={null}
use Inertia\Inertia;

class EventsController extends Controller
{
    public function show(Event $event)
    {
        return Inertia::render('Event/Show', [
            'event' => $event->only(
                'id',
                'title',
                'start_date',
                'description'
            ),
        ]);

        // Alternatively, you can use the inertia() helper...
        return inertia('Event/Show', [
            'event' => $event->only(
                'id',
                'title',
                'start_date',
                'description'
            ),
        ]);
    }
}
```

<Tip>
  Để đảm bảo trang tải nhanh, chỉ trả về lượng dữ liệu tối thiểu mà trang cần.
</Tip>

<Note>
  Hãy nhớ rằng mọi dữ liệu controller trả về đều có thể nhìn thấy ở phía client, vì vậy phải loại bỏ thông tin nhạy cảm.
</Note>

## Property

Để truyền dữ liệu từ máy chủ vào page component, bạn có thể dùng property. Props có thể nhận nhiều loại giá trị, gồm primitive, array, object và một số kiểu riêng của Laravel được tự động resolve:

```php theme={null}
use App\Models\User;
use Illuminate\Http\Resources\Json\JsonResource;

Inertia::render('Dashboard', [
    // Primitive values
    'title' => 'Dashboard',
    'count' => 42,
    'active' => true,

    // Arrays and objects
    'settings' => ['theme' => 'dark', 'notifications' => true],

    // Arrayable objects (Collections, Models, etc.)
    'user' => auth()->user(), // Eloquent model
    'users' => User::all(), // Eloquent collection

    // API Resources
    'profile' => new UserResource(auth()->user()),

    // Responsable objects
    'data' => new JsonResponse(['key' => 'value']),

    // Closures
    'timestamp' => fn() => now()->timestamp,
]);
```

Các object `Arrayable` như Eloquent model và collection tự động được chuyển đổi qua phương thức `toArray()`. Các object `Responsable` như API resource và JSON response được resolve qua phương thức `toResponse()`.

## Interface `ProvidesInertiaProperty`

Khi truyền props vào component, đôi khi bạn muốn tạo custom class có khả năng tự chuyển đổi sang định dạng dữ liệu thích hợp. Trong khi interface `Arrayable` của Laravel chỉ chuyển object thành array, Inertia cung cấp interface `ProvidesInertiaProperty` mạnh hơn với khả năng transform theo context.

Interface này yêu cầu method `toInertiaProperty`, nhận object `PropertyContext` chứa property key (`$context->key`), toàn bộ props của trang (`$context->props`) và request instance (`$context->request`).

```php theme={null}
use Inertia\PropertyContext;
use Inertia\ProvidesInertiaProperty;

class UserAvatar implements ProvidesInertiaProperty
{
    public function __construct(protected User $user, protected int $size = 64)
    {
        //
    }

    public function toInertiaProperty(PropertyContext $context): mixed
    {
        return $this->user->avatar
            ? Storage::url($this->user->avatar)
            : "https://ui-avatars.com/api/?name={$this->user->name}&size={$this->size}";
    }
}
```

Sau khi định nghĩa, bạn có thể dùng class này trực tiếp làm giá trị prop.

```php theme={null}
Inertia::render('Profile', [
    'user' => $user,
    'avatar' => new UserAvatar($user, 128),
]);
```

`PropertyContext` cho phép truy cập property key, qua đó hỗ trợ các pattern mạnh như merge với dữ liệu dùng chung.

```php theme={null}
use Inertia\Inertia;
use Inertia\PropertyContext;
use Inertia\ProvidesInertiaProperty;

class MergeWithShared implements ProvidesInertiaProperty
{
    public function __construct(protected array $items = [])
    {
        //
    }

    public function toInertiaProperty(PropertyContext $context): mixed
    {
        // Access the property key to get shared data
        $shared = Inertia::getShared($context->key, []);

        // Merge with the new items
        return array_merge($shared, $this->items);
    }
}

// Usage
Inertia::share('notifications', ['Welcome back!']);

return Inertia::render('Dashboard', [
    'notifications' => new MergeWithShared(['New message received']),
    // Result: ['Welcome back!', 'New message received']
]);
```

## Interface `ProvidesInertiaProperties`

Trong một số tình huống, bạn muốn gom các prop liên quan lại để tái sử dụng trên nhiều trang. Bạn có thể làm điều đó bằng cách implement interface `ProvidesInertiaProperties`.

Interface này yêu cầu method `toInertiaProperties` trả về array các cặp key-value. Method nhận object `RenderContext` chứa tên component (`$context->component`) và request instance (`$context->request`).

```php theme={null}
use App\Models\User;
use Illuminate\Container\Attributes\CurrentUser;
use Inertia\RenderContext;
use Inertia\ProvidesInertiaProperties;

class UserPermissions implements ProvidesInertiaProperties
{
    public function __construct(#[CurrentUser] protected User $user)
    {
        //
    }

    public function toInertiaProperties(RenderContext $context): array
    {
        return [
            'canEdit' => $this->user->can('edit'),
            'canDelete' => $this->user->can('delete'),
            'canPublish' => $this->user->can('publish'),
            'isAdmin' => $this->user->hasRole('admin'),
        ];
    }
}
```

Bạn có thể dùng trực tiếp các prop class này trong method `render()` và `with()`.

```php theme={null}
public function index(UserPermissions $permissions)
{
    return Inertia::render('UserProfile', $permissions);

    // or...

    return Inertia::render('UserProfile')->with($permissions);
}
```

Bạn cũng có thể kết hợp nhiều prop class với các prop khác trong một array:

```php theme={null}
public function index(UserPermissions $permissions)
{
    return Inertia::render('UserProfile', [
        'user' => auth()->user(),
        $permissions,
    ]);

    // or using method chaining...

    return Inertia::render('UserProfile')
        ->with('user', auth()->user())
        ->with($permissions);
}
```

## Dữ liệu root template

Có những trường hợp bạn muốn truy cập dữ liệu prop trong root Blade template của ứng dụng. Ví dụ, bạn có thể muốn thêm meta description, Twitter Card meta tag hoặc Facebook Open Graph meta tag. Bạn có thể truy cập dữ liệu này qua biến `$page`.

```blade theme={null}
<meta name="twitter:title" content="{{ $page['props']['event']->title }}">
```

Đôi khi bạn muốn cung cấp dữ liệu cho root template nhưng không gửi dữ liệu đó đến page component JavaScript. Có thể thực hiện bằng method `withViewData`.

```php theme={null}
return Inertia::render('Event', ['event' => $event])
    ->withViewData(['meta' => $event->meta]);
```

Sau khi gọi `withViewData`, bạn có thể truy cập dữ liệu đã định nghĩa như cách truy cập biến Blade template thông thường.

```blade theme={null}
<meta name="description" content="{{ $meta }}">
```

## Kích thước response tối đa

Để hỗ trợ điều hướng history phía client, tất cả response Inertia từ máy chủ được lưu trong history state của trình duyệt. Tuy nhiên, hãy lưu ý một số trình duyệt giới hạn lượng dữ liệu có thể lưu trong history state.

Ví dụ, [Firefox](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState) giới hạn 16 MiB và ném lỗi `NS_ERROR_ILLEGAL_VALUE` nếu vượt quá giới hạn. Thông thường con số này lớn hơn rất nhiều so với lượng dữ liệu thực tế bạn cần trong ứng dụng.

***

## Tài liệu chính thức

Bài dịch này được đối chiếu từ [tài liệu Inertia.js v2 chính thức](https://inertiajs.com/docs/v2/the-basics/responses). Nếu có khác biệt do phiên bản hoặc cập nhật mới, hãy ưu tiên tài liệu chính thức làm nguồn tham chiếu.
