Laravel 統一介面獲取用戶提交資料,無論 GET、POST、JSON 均可用 Input::get():
$name = Input::get('name'); // 單一欄位
$name = Input::get('name', 'Sally'); // 預設值
$hasName = Input::has('name'); // 是否存在
$allInput = Input::all(); // 所有輸入
$only = Input::only('username', 'password');
$except = Input::except('credit_card');
$name = Input::get('products.0.name'); // 點號訪問巢狀陣列
Backbone.js 等前端框架以 JSON 提交時,Input::get 使用方式無差別。
Laravel 自動加密並簽名 Cookie,客戶端竄改會導致失效:
$value = Cookie::get('name');
$response = Response::make('Hello');
$response->withCookie(Cookie::make('name', 'value', $minutes));
Cookie::queue('name', 'value', $minutes); // 回應建立前即可呼叫
$cookie = Cookie::forever('name', 'value');
表單驗證失敗重導時保留用戶輸入:
Input::flash(); // 全部存入 Session
Input::flashOnly('username', 'email');
Input::flashExcept('password');
return Redirect::to('form')->withInput();
return Redirect::to('form')->withInput(Input::except('password'));
$username = Input::old('username');
$file = Input::file('photo');
if (Input::hasFile('photo')) { ... }
file() 回傳 Symfony\Component\HttpFoundation\File\UploadedFile 實例(繼承 SplFileInfo):
Input::file('photo')->move($destinationPath, $fileName);
$path = Input::file('photo')->getRealPath();
$size = Input::file('photo')->getSize();
$mime = Input::file('photo')->getMimeType();
$uri = Request::path(); // 請求 URI
$url = Request::url(); // 完整 URL
$segment = Request::segment(1); // URI 片段
$contentType = Request::header('Content-Type');
$pathInfo = Request::server('PATH_INFO');
$isAjax = Request::ajax();
$isSecure = Request::secure();
$format = Request::format(); // 基於 Accept 標頭
// Controller
public function store() {
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::back()->withInput()->withErrors($validator);
}
// ...
}
// Blade 視圖
<input name="email" value="{{ old('email') }}">
@if ($errors->has('email'))
<span class="error">{{ $errors->first('email') }}</span>
@endif
Laravel 的 Input/Request 抽象層統一了 HTTP 請求資料的存取方式,內建加密 Cookie、舊輸入保留、檔案上傳封裝等常用功能,搭配驗證器可快速構建安全的表單處理流程。