当前位置:网站首页>Laravel document sorting 6. Response
Laravel document sorting 6. Response
2022-06-25 04:19:00 【Angry devil】
Preface :Laravel Document sorting , Only for record , Nothing else .
1、laravel The basic response of the framework
Route::get('/', function () {
return 'Hello World';
});
Ps:
A、laravel The basic response of the framework , Simply return a string through a route or controller
B、 The specified string will be automatically converted to by the framework HTTP Respond to
2、 The usual return , You need to return a complete Illuminate\Http\Response example , Such as :
use Illuminate\Http\Response;
Route::get('home', function () {
return (new Response($content, $status))
->header('Content-Type', $value);
});
Ps: The reason for returning a complete instance , To facilitate the definition of headers and status codes
Response Class inherited by instance :Symfony\Component\HttpFoundation\Response
3、 About response , For convenience , You can use auxiliary functions response, Such as :
Route::get('home', function () {
return response($content, $status)
->header('Content-Type', $value);
});
4、 Most response methods can be called in a chain , Such as attaching headers to responses :
return response($content)
->header('Content-Type', $type)
->header('X-Header-One', 'Header Value')
->header('X-Header-Two', 'Header Value');
5、 additional cookie To response
return response($content)->header('Content-Type', $type)
->withCookie('name', 'value');
WithCookie Method has some additional parameters :
->withCookie($name, $value, $minutes, $path, $domain, $secure, $httpOnly)
Ps: By default ,laravel The framework will be right cookie To encrypt , Users cannot read and modify , however , If some , You don't want to encrypt , available App\Http\Middleware\EncryptCookies Middleware $except attribute , Such as :
/**
* No need to be encrypted cookies name .
*
* @var array
*/
protected $except = [
'cookie_name',
];
6、 Auxiliary function response() Without any parameters , The return implementation is ?
Illuminate\Contracts\Routing\ResponseFactory Of contract Realization
7、 The response of the view
return response()->view('hello', $data)->header('Content-Type', $type);
8、json Respond to
return response()->json(['name' => 'Abigail', 'state' => 'CA']);
Ps:json() Method will automatically set the Content-Type Set to application/json, And through PHP Of json_encode() Method to convert the array to json
9、jsonP Respond to
return response()->json(['name' => 'Abigail', 'state' => 'CA'])
->setCallback($request->input('callback'));
Ps:jsonp The response is relative to json Respond to , Just add one more setCallback Method
10、 File download response
return response()->download($pathToFile);
Ps:download Method to force the user browser to generate a response for downloading a file with a specified path .
Download There is another method 2、3 Parameters , They are file names 、http header , as follows :
return response()->download($pathToFile, $name, $headers);
11、 Redirect response
Route::get('dashboard', function () {
return redirect('home/dashboard');
});
Ps: Use redirect() Auxiliary function , Is the simplest redirect response
Common useful examples : For example, the user submits an empty form , Just let him go back , Continue to that page , This is the time , be used back function , Such as
Route::post('user/profile', function () {
// Verify the request ...
return back()->withInput();
});
12、 Redirect to named route
return redirect()->route('login');
Ps: If the route has parameters , In the route The second argument to the method
// Redirect to the following URI: profile/{id}
return redirect()->route('profile', [1]);
If the route parameter is Eloquent Model id, Then the model is directly transferred to ,id Will be extracted
return redirect()->route('profile', [$user]);
13、 Redirect to controller behavior
return redirect()->action('[email protected]');
Ps: If the controller route requires parameters , It's in action Method , Pass in the second parameter
return redirect()->action('[email protected]', [1]);
14、 Redirect and add session Flash Data
Usually redirect to a new url, The data will be written to session. therefore , This is the time , Flash data is very convenient , Such as :
Route::post('user/profile', function () {
// Update the user's personal data ...
return redirect('dashboard')->with('status', 'Profile updated!');
});
sync
After redirecting to a new page , If you still want to get the data on this page , Use blade The grammar of :
@if (session('status'))
<div class="alert alert-success">
{ { session('status') }}
</div>
@endif
15、 Response macro
If you want to define a response that is reused in many routers and controllers , have access to
Illuminate\Contracts\Routing\ResponseFactory Method of implementation macro, give an example :
From the service provider boot Method
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Routing\ResponseFactory;
class ResponseMacroServiceProvider extends ServiceProvider
{
/**
* Provide services that run after registration .
*
* @param ResponseFactory $factory
* @return void
*/
public function boot(ResponseFactory $factory)
{
$factory->macro('caps', function ($value) use ($factory) {
return $factory->make(strtoupper($value));
});
}
}
Ps:macro() The first argument to the method is the macro name , The second parameter is the closure function .
The closure function of the macro will be in responseFactory Implementation or auxiliary function of response The macro name is called when it is run .
Such as :
return response()->caps('foo');
边栏推荐
- Cesium loading display thermal diagram
- 升级cmake
- Vigilance against over range collection of privacy - ten mobile app violations
- Where is the red area of OpenCV?
- 数学分析_笔记_第3章:极限
- "Renaissance" in the digital age? The bottom digital collection makes people happy and sad
- 讲座记录《惯性导航的新应用——惯性测量》
- Cesium graphic annotation circle, square, polygon, ellipse, etc
- Cesium 拖拽3D模型
- 虽然传统意义上的互联网早已不复存在,但这并不代表互联网早已消失不再
猜你喜欢

1280_ C language to find the average value of two unsigned integer
![[harmony OS] [ark UI] basic ETS context operations](/img/fb/a1b8463ba160e6c5aa23d671a0c245.png)
[harmony OS] [ark UI] basic ETS context operations

Crawler crawls Sina Weibo data
![[team learning] SQL programming language notes - task04](/img/3e/c75f5b4610c6b6700567fe75cd2339.png)
[team learning] SQL programming language notes - task04

WMS仓储管理系统的使用价值,你知道多少

navicat可不可以直接操作安卓数据库SQLite

Hot and cold, sweet and sour, want to achieve success? Dengkang oral, the parent company of lengsuanling, intends to be listed on the main board of Shenzhen Stock Exchange

1.初识半音阶口琴

Development of trading system (II) -- market data

How to use ide to automatically sign and debug Hongmeng application
随机推荐
Qt编译数据库插件通用步骤说明
如何绘制产业招商地图
【LeetCode】148. 排序链表
AI quantitative transaction (II) -- tushare financial data framework
Flutter Builder & futurebuilder components
Development of trading system (XIII) -- Analysis of quickfix source code
Development of trading system (VIII) -- Construction of low delay network
Interview with Mo Tianlun | ivorysql wangzhibin - ivorysql, an Oracle compatible open source database based on PostgreSQL
mysql的tinyint字段类型判断的疑惑
文本关键词提取:ansj
UCLA | 用于黑盒优化的生成式预训练
MySQL order by
练习:仿真模拟福彩双色球——中500w巨奖到底有多难?跑跑代码就晓得了。
Where is the red area of OpenCV?
BSC parsing input data of transaction
@RequestBody解决获取参数为null
Siddhartha: the book of life can be regurgitated frequently
Cesium 加载显示热力图
Simple integration of client go gin -update
论文阅读《LSD-SLAM: Large-Scale Direct Monocular SLAM》