laravel

laravel Request 请求

2019-02-27  本文已影响0人  空气KQ

获取请求路径

path()

http://domain.com/user/1
$path = $request->path();
则 path 方法将会返回 user/1:

is 验证请求路径是否与给定模式匹配

if($request->is('user/*')){
    //
}

一般可用于权限判断或者是选中导航状态等

获取请求 URL
// 不包含查询字符串 $url = $request->url();

包含查询字符串fullUrl()
$url_with_query = $request->fullUrl();

请求方法判断method()

$method = $request->method(); // GET/POST

if($request->isMethod('post')){ 
    // true or false
}

获取请求输入

单个输入值 $request->input('name');

获取所有输入值request->all();数组格式获取所有输入值

处理表单数组输入时,可以使用”.”来访问数组输入

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

从查询字符串中获取输入
$name = $request->query('name');

动态属性获取输入
$name = $request->name;
首先会在请求中查找参数的值,如果不存在,还会到路由参数中查找

获取输入的部分数据
可以使用 only 或 except 方法

判断请求参数是否存在

if ($request->has('name')) { // }
查询多个参数

if ($request->has(['name', 'email'])) {
    //
}

判断参数存在且参数值不为空,可以使用 filled 方法:

if ($request->filled('name')) {
    //
}

将输入存储到 Session

$request->flash();

flashOnly 和 flashExcept 方法将输入数据子集存放到 Session 中,这些方法在 Session 之外保存敏感信息时很有用,该功能适用于登录密码填写错误的场景

$request->flashOnly('username', 'email');
$request->flashExcept('password');

将输入存储到 Session 然后重定向

redirect 之后调用 withInput

return redirect('form')->withInput();
return redirect('form')->withInput($request->except('password'));

取出上次请求数据

$username = $request->old('username');
old('name')

从请求中取出Cookie

$request->cookie('name');
$value = Cookie::get('name');

Cookie 到响应

return response('欢迎来到 Laravel 学院')->cookie(
    'name', '学院君', $minutes, $path, $domain, $secure, $httpOnly
);

生成 Cookie 实例

以使用全局辅助函数 cookie,该 Cookie 只有在添加到响应实例上才会发送到客户端

$cookie = cookie('name', '学院君', $minutes);
return response('欢迎来到 Laravel 学院')->cookie($cookie);

文件上传

获取上传文件file

$file = $request->file('photo');
$file = $request->photo;

是否存在

if ($request->hasFile('photo')) {
    //
}

否上传成功

if ($request->file('photo')->isValid()){
    //
}

文件路径和扩展名

$path = $request->photo->path();
$extension = $request->photo->extension();

总结

Request 说白了就是封装了原本属于post,get,put等方法的汇聚,还封装了cookie。

上一篇 下一篇

猜你喜欢

热点阅读