laravel 請求request 接收參數

獲取請求輸入

獲取全部輸入值json

你能夠使用 all 方法以數組格式獲取全部輸入值:數組

$input = $request->all();

獲取單個輸入值app

使用一些簡單的方法,就能夠從 Illuminate\Http\Request 實例中訪問用戶輸入。你不須要關心請求所使用的 HTTP 請求方法,由於對全部請求方式的輸入都是經過 input 方法獲取用戶輸入:spa

$name = $request->input('name');

你還能夠傳遞一個默認值做爲第二個參數給 input 方法,若是請求輸入值在當前請求未出現時該值將會被返回:code

$name = $request->input('name', 'Sally');

處理表單數組輸入時,能夠使用」.」來訪問數組輸入:路由

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

經過動態屬性獲取輸入input

此外,你還能夠經過使用 Illuminate\Http\Request 實例上的動態屬性來訪問用戶輸入。例如,若是你的應用表單包含 name 字段,那麼能夠像這樣訪問提交的值:it

$name = $request->name;

使用動態屬性的時候,Laravel 首先會在請求中查找參數的值,若是不存在,還會到路由參數中查找。io

獲取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')) {
    //
}
相關文章
相關標籤/搜索