Laravel 中的 HTTP 請求與回應

Laravel 提供方便的方式來處理 HTTP 請求與回應。可以透過 Illuminate\Http\Request 類別或 request() 輔助函式處理請求,並使用 response() 建立各類型回應,如純文字、JSON、重定向、下載檔案等。


📥 request() - 處理請求

使用 request() 可取得當前請求實例,常見操作如下:

// 取得參數
$name = request('name');
$id = request('id');

// 上傳檔案判斷與取得
if (request()->hasFile('avatar')) {
    $file = request()->file('avatar');
}

// 預設值
$age = request('age', fn() => 18);

也可於 Controller 中注入 Request 類別:

use Illuminate\Http\Request;

public function update(Request $request, $id)
{
    $name = $request->input('name');
}

🧩 常用 Request 方法

方法 說明
input($key, $default) 取得輸入值
only($keys) 只取得指定鍵
except($keys) 排除指定鍵
all() 全部輸入值
has($key) 是否存在輸入鍵
header($key) 取得標頭
method() HTTP 方法 (GET、POST)
isMethod($method) 判斷請求方法
url() 請求 URL
fullUrl() URL + Query 字串
route($param) 當前路由名稱或參數
segment($index) URL 片段
segments() 全部片段陣列

📤 response() - 建立回應

可用於產生不同類型的 HTTP 回應。

return response($content, $status, $headers);

🧩 常用 Response 方法

方法 說明
make($content, $status) 建立基本回應
json($data) 回傳 JSON
view($view, $data) 回傳視圖
file($file) 顯示檔案內容
download($file, $name) 下載檔案
redirect($url) 重定向
header($key, $value) 設定單一標頭
withHeaders([...]) 多個標頭
cookie($name, $value, $minutes) 設定 cookie

✨ 回應範例

1. 純文字

return response('Hello World');

2. 自訂狀態碼

return response('Unauthorized', 401);

3. JSON 回應

return response()->json(['name' => 'John', 'age' => 30]);

4. 設定標頭

return response('Hello')->header('Content-Type', 'text/plain');

5. 下載檔案

return response()->download(storage_path('file.pdf'));

6. 重定向

return redirect('/home');
return response('Hello')->cookie('token', 'abc123', 60);

8. 顯示檔案內容

return response()->file(public_path('image.jpg'));

9. 顯示視圖

return response()->view('welcome', ['user' => 'Jack']);