所有路由和控制器处理完业务逻辑之后都会返回一个发送到用户浏览器的响应,Laravel 提供了多种不同的方式来返回响应,最基本的响应就是从路由或控制器返回一个简单的字符串,框架会自动将这个字符串转化为一个完整的 HTTP 响应.
1、字符串
Route::get('/', function () {return 'Hello World String All';
});
2、数组
除了从路由或控制器返回字符串之外,还可以返回数组。框架会自动将数组转化为一个 JSON 响应:
Route::get('/', function () {return [1,2,3,4,5,6,7,8,9,10];
});
3、Response 对象
返回完整的 Response 实例允许你自定义响应的 HTTP 状态码和响应头信息。
Route::get('home', function () {return response('Hello World Test', 200)->header('Content-Type', 'text/plain');
});
4、添加头信息
大部分的响应方法都是可链式调用的,使得创建响应实例的过程更具可读性。
return response($content)->header('Content-Type', $type)->header('X-Header-One', 'Header Val')->header('X-Header-Two', 'Header Val');
或者 使用 withHeaders 方法
return response($content)->withHeaders(['Content-Type' => $type,'X-Header-One' => 'Header Val','X-Header-Two' => 'Header Val',]);
5、添加 Cookies 到响应
可以使用响应上的 cookie 方法轻松地将为响应增加 Cookies:
return response($content)->header('Content-Type', $type)->cookie('name', 'value', $minutes);
6、重定向
并且包含用户需要重定向至另一个 URL 所需的头信息。
Route::get('admin', function () {return redirect('home/index');
});
或者可以将用户重定向到之前的位置,提交的表单无效时,可以使用全局辅助函数 back 来执行此操作。
Route::post('user/profile', function () {// 验证请求return back()->withInput();
});
7、重定向到命名路由
// 以下三种方式进行操作
return redirect()->route('login');
return redirect()->route('profile', ['id' => 1]);
return redirect()->route('profile', [$user]);
8、重定向到控制器
需要把控制器和action的名称传递给 action 方法。
// 不带参数的方法
return redirect()->action('HomeController@index');
// 传递参数的方法
return redirect()->action('UserController@profile', ['id' => 1]);
// 重定向到应用外的域名
return redirect()->away('https://www.baidu.com');
// 重定向并使用闪存的 Session 数据,使用status把数据存入session中
Route::post('user/profile', function () {return redirect('dashboard')->with('status', 'Profile updated!');
});
9、其它的响应
视图响应
return response()->view('hello', $data, 200)->header('Content-Type', $type);
json响应
return response()->json(['name' => 'AAC','state' => '200'
]);
jsonp响应
return response()->json(['name' => 'Abigail', 'state' => 'CA'])->withCallback($request->input('callback'));
10、文件下载
download 方法可以用于生成强制用户浏览器下载给定路径文件的响应
return response()->download($pathToFile);
return response()->download($pathToFile, $name, $headers);
return response()->download($pathToFile)->deleteFileAfterSend();
看完本文有收获?点赞、分享是最大的支持!