> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# HTTP Request

> 說明如何使用 Laravel 的 Illuminate\Http\Request 物件取得 HTTP 請求資料。

## 什麼是 Request 物件

`Illuminate\Http\Request` 是以物件導向處理應用程式所收到的 HTTP 請求的類別。
可存取請求中所有資訊，如表單資料、query string、檔案、header 等。

## 於控制器注入 Request

在控制器方法上以 `Illuminate\Http\Request` type-hint，Laravel 的 service container 會自動注入 request 實例。

```php theme={null}
<?php

namespace App\Http\Controllers;

use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function store(Request $request): RedirectResponse
    {
        $name = $request->input('name');

        // 儲存使用者的處理...

        return redirect('/users');
    }
}
```

在路由 closure 中也可以同樣 type-hint。

```php theme={null}
use Illuminate\Http\Request;

Route::get('/', function (Request $request) {
    // ...
});
```

### 與路由參數同時使用

當控制器方法也接受路由參數時，將路由參數寫在 `Request` 之後：

```php theme={null}
use App\Http\Controllers\UserController;

Route::put('/user/{id}', [UserController::class, 'update']);
```

```php theme={null}
public function update(Request $request, string $id): RedirectResponse
{
    // 用 $request 存取請求資料，用 $id 存取路由參數

    return redirect('/users');
}
```

## 取得請求資料

### 取得所有輸入資料

`all` 方法將所有輸入資料以陣列形式取得。
無論來自 HTML 表單或 XHR 請求都可使用。

```php theme={null}
$input = $request->all();
```

### 取得特定欄位

`input` 方法不論 HTTP 方法為何，都會從整個請求 payload（含 query string）取得值。

```php theme={null}
$name = $request->input('name');
```

第 2 個引數可指定值不存在時的預設值：

```php theme={null}
$name = $request->input('name', 'Sally');
```

陣列輸入以 dot notation 存取。

```php theme={null}
$name = $request->input('products.0.name');

$names = $request->input('products.*.name');
```

### 取得 query string

`query` 方法只會從 query string（URL 中 `?` 之後的部分）取得值。

```php theme={null}
$name = $request->query('name');

$name = $request->query('name', 'Helen');

// 以陣列取得所有 query string
$query = $request->query();
```

<Info>
  `input` 對象是請求 body 與 query string 兩者，`query` 只針對 query string。
  若要區分表單 POST 資料與 URL 參數，請使用 `query`。
</Info>

### 型別化取得

除 `input` 外，也提供指定型別取得輸入值的方法。

```php theme={null}
// 以字串取得（Stringable 實例）
$name = $request->string('name')->trim();

// 以整數取得
$perPage = $request->integer('per_page');

// 以布林值取得（"1"、"true"、"on"、"yes" → true）
$archived = $request->boolean('archived');

// 以陣列取得
$versions = $request->array('versions');

// 以 Carbon 實例取得日期
$birthday = $request->date('birthday');
```

### 動態屬性

也可以將欄位名稱作為屬性直接存取。

```php theme={null}
$name = $request->name;
```

<Tip>
  動態屬性會先從請求 payload 找值，若找不到再搜尋路由參數。
</Tip>

### 取得輸入資料的一部分

`only` 與 `except` 可取得輸入資料的子集。

```php theme={null}
$input = $request->only(['username', 'password']);

$input = $request->except(['credit_card']);
```

## 輸入的存在確認

以 `has` 方法確認值是否包含在請求中。

```php theme={null}
if ($request->has('name')) {
    // ...
}

// 確認是否全部包含多個 key
if ($request->has(['name', 'email'])) {
    // ...
}
```

要排除空字串以確認值是否存在，使用 `filled`。

```php theme={null}
if ($request->filled('name')) {
    // ...
}
```

當值不存在或為空字串時，使用 `isNotFilled`。

```php theme={null}
if ($request->isNotFilled('name')) {
    // ...
}
```

## 請求路徑與方法確認

### 取得與確認路徑

```php theme={null}
// 取得路徑（例如："foo/bar"）
$uri = $request->path();

// 確認是否符合樣式（可用萬用字元 *）
if ($request->is('admin/*')) {
    // ...
}

// 確認是否符合具名路由
if ($request->routeIs('admin.*')) {
    // ...
}
```

### 取得 URL

```php theme={null}
// 不含 query string 的 URL
$url = $request->url();

// 含 query string 的 URL
$urlWithQueryString = $request->fullUrl();
```

### 確認 HTTP 方法

以 `isMethod` 確認 HTTP 方法。

```php theme={null}
$method = $request->method();

if ($request->isMethod('post')) {
    // 只處理 POST 請求
}
```

## 檔案上傳

### 取得已上傳的檔案

以 `file` 方法取得上傳的檔案。
回傳 `Illuminate\Http\UploadedFile` 實例。

```php theme={null}
$file = $request->file('photo');

// 也可用動態屬性取得
$file = $request->photo;
```

要確認檔案是否存在，使用 `hasFile`。

```php theme={null}
if ($request->hasFile('photo')) {
    // ...
}
```

### 儲存檔案

以 `store` 方法將檔案儲存到 storage。
檔名會自動產生。

```php theme={null}
// 儲存到預設 disk 的 "images" 目錄
$path = $request->photo->store('images');

// 儲存到 S3
$path = $request->photo->store('images', 's3');
```

要指定檔名時使用 `storeAs`。

```php theme={null}
$path = $request->photo->storeAs('images', 'filename.jpg');
```

<Warning>
  接受檔案上傳時，務必驗證檔案類型與大小。
  建議透過驗證安全地處理。
</Warning>

## 範例：接收表單資料

以下是在控制器接收使用者註冊表單資料的範例。

```php theme={null}
<?php

namespace App\Http\Controllers;

use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class RegisterController extends Controller
{
    public function store(Request $request): RedirectResponse
    {
        // 取得表單資料
        $name = $request->input('name');
        $email = $request->input('email');
        $password = $request->input('password');

        // 只取所需資料
        $data = $request->only(['name', 'email', 'password']);

        // 建立使用者的處理...

        return redirect('/dashboard');
    }
}
```

定義對應的路由：

```php theme={null}
use App\Http\Controllers\RegisterController;

Route::post('/register', [RegisterController::class, 'store']);
```

## 後續步驟

<Card title="Middleware" icon="shield" href="/zh-TW/middleware">
  複習用來過濾請求的 middleware 的使用方式。
</Card>


## Related topics

- [授權（Gate 與 Policy）](/zh-TW/authorization.md)
- [驗證](/zh-TW/validation.md)
- [Laravel Octane](/zh-TW/octane.md)
- [GeneratorCommand — 自訂 make: 指令的實作](/zh-TW/advanced/generator-command.md)
- [InteractsWithData trait](/zh-TW/advanced/interacts-with-data.md)
