獲取請求輸入
獲取所有輸入值
你可以使用 all
方法以數組格式獲取所有輸入值:
$input = $request->all();
獲取單個輸入值
使用一些簡單的方法,就可以從 Illuminate\Http\Request
實例中訪問用戶輸入。你不需要關心請求所使用的 HTTP 請求方法,因為對所有請求方式的輸入都是通過 input
方法獲取用戶輸入:
$name = $request->input('name');
你還可以傳遞一個默認值作為第二個參數給 input
方法,如果請求輸入值在當前請求未出現時該值將會被返回:
$name = $request->input('name', 'Sally');
處理表單數組輸入時,可以使用”.”來訪問數組輸入:
$input = $request->input('products.0.name');
$names = $request->input('products.*.name');
通過動態屬性獲取輸入
此外,你還可以通過使用 Illuminate\Http\Request
實例上的動態屬性來訪問用戶輸入。例如,如果你的應用表單包含 name
字段,那么可以像這樣訪問提交的值:
$name = $request->name;
使用動態屬性的時候,Laravel 首先會在請求中查找參數的值,如果不存在,還會到路由參數中查找。
獲取JSON輸入值
發送JSON請求到應用的時候,只要 Content-Type
請求頭被設置為 application/json
,都可以通過 input
方法獲取 JSON 數據,還可以通過“.”號解析數組:
$name = $request->input('user.name');
獲取輸入的部分數據
如果你需要取出輸入數據的子集,可以使用 only
或 except
方法,這兩個方法都接收一個數組或動態列表作為唯一參數:
$input = $request->only(['username', 'password']);
$input = $request->only('username', 'password');
$input = $request->except(['credit_card']);
$input = $request->except('credit_card');
only
方法返回你所請求的所有鍵值對,即使輸入請求中不包含你所請求的鍵,當對應鍵不存在時,對應返回值為 null
,如果你想要獲取輸入請求中確實存在的部分數據,可以使用 intersect
方法:
$input = $request->intersect(['username', 'password']);
判斷輸入值是否存在
判斷值是否在請求中存在,可以使用 has
方法,如果值出現過了且不為空,has
方法返回 true
:
if ($request->has('name')) {
//
}