当前位置:网站首页>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');
边栏推荐
- Is opencv open source?
- Crawler crawls Sina Weibo data
- 1.初识半音阶口琴
- What is the difference between learning code, rolling code and fixed code? The number of repeated codes, coding capacity and the principle of rolling code
- Windows 2003 64 bit system PHP running error: 1% is not a valid Win32 Application
- How much do you know about the use value of WMS warehouse management system
- SEO的5大关键指标:排名+流量+会话+停留时长+跳出率
- 1. Phase II of the project - user registration and login
- 【Proteus仿真】Arduino UNO按键控制数码管闪烁增/减显示
- opencv 红色区域在哪里?
猜你喜欢

La gamme NFT Color, qui représente la diversité, est en ligne sur la plate - forme du marché Sandbox

代表多样性的彩色 NFT 系列上线 The Sandbox 市场平台

如何绘制产业招商地图

Lecture record: history and development of strapdown inertial navigation solution

2. play the chromatic harmonica

95% 程序员都在这里摸鱼……

Development of trading system (III) - risk control system

2022-06-21-flink-49 (I. SQL manual)

Development of trading system (VI) -- HFT high frequency trading

讲座记录《惯性导航的新应用——惯性测量》
随机推荐
Text keyword extraction: ansj
WMS仓储管理系统的使用价值,你知道多少
【openwrt】推荐一个国内开发的openwrt的版本,iStoreOS简介,非常好用,主要是做了一些优化。解决了汉化的问题。
Turn 2D photos into 3D models to see NVIDIA's new AI "magic"!
讲座记录《多种空间大地测量技术的数据处理方法和应用》
PHP code audit 2 - these functions must be known and understood
@Requestbody solution get parameter is null
opencv怎么安装?opencv下载安装教程
Acmstreamopen return value problem
IntStream API介绍
AI quantitative transaction (I) -- Introduction to quantitative transaction
How to quickly deliver high-value software
LeetCode 剑指Offer II 091 粉刷房子[动态规划] HERODING的LeetCode之路
Where is the red area of OpenCV?
佐喃社区
"Renaissance" in the digital age? The bottom digital collection makes people happy and sad
"Comment positionner l'industrie" dans la planification industrielle locale / parc
微信小程序中的列表渲染
练习:仿真模拟福彩双色球——中500w巨奖到底有多难?跑跑代码就晓得了。
The 5th series of NFT works of missing parts was launched on the sandbox market platform