


How to create response in Laravel 5.5? Introduction to creating responses (code)
How does Laravel 5.5 create responses? Many people may not be very clear about it, so next I will introduce to you how to create an http response in Laravel 5.5 and introduce other response types.
Create response
String & Array
All routes and controllers will return a response sent to the user's browser after processing the business logic Response, Laravel provides many different ways to return responses. The most basic response is to return a simple string from the route or controller. The framework will automatically convert this string into a complete HTTP response.
Route::get('/', function () { return 'Hello World'; });
In addition to returning strings from routes or controllers, you can also return arrays. The framework will automatically convert the array into a JSON response.
Route::get('/', function () { return [1, 2, 3]; });
Note: You can also return Eloquent collections from routes or controllers, which will also be automatically converted into a JSON response.
Response object
Usually, we don’t just simply return a string or array from the route. In most cases, a complete Illuminate\Http\Response instance or view is returned.
Returning a complete Response instance allows you to customize the HTTP status code and header information of the response. Response instances inherit from the Symfony\Component\HttpFoundation\Response base class, which provides a series of methods for creating HTTP responses.
Route::get('/', function () { return response('Hello World', 200) ->header('Content-Type', 'text/plain'); });
Add response header
Most response methods can be called in the form of method chains, so that responses can be constructed streamingly (streaming interface mode). For example, you can use the header method to add a series of response headers before sending the response to the user.
return response($content) ->header('Content-Type', $type) ->header('X-Header-One', 'Header Value') ->header('X-Header-Two', 'Header Value');
Or you can use the withHeaders method to specify an array of header information to add to the response.
return response($content) ->withHeaders([ 'Content-Type' => $type, 'X-Header-One' => 'Header Value', 'X-Header-Two' => 'Header Value', ]);
Adding Cookies to Responses
Cookies can be easily added to responses using the cookie method on the response instance. For example, you can use the cookie method to generate a cookie and add it to the response instance.
return response($content) ->header('Content-Type', $type) ->cookie('name', 'value', $minutes);
The cookie method can also receive more additional optional parameters that are less frequently used. Generally speaking, these parameters have similar purposes and meanings to the setcookie method natively provided by PHP.
->cookie($name, $value, $minutes, $path, $domain, $secure, $httpOnly)
Alternatively, you can use the Cookie facade to add cookies to the response in a "queue" form. The queue method receives as parameters a Cookie instance or the parameters necessary to create a cookie that will be added to the response before it is sent to the browser.
Route::get('cookie/response', function() { Cookie::queue(Cookie::make('site', 'www.baidu.com',1)); Cookie::queue('author', 'admin', 1); return response('Hello Laravel', 200) ->header('Content-Type', 'text/plain'); });
Visit http://www.adm.devp/cookie/response in your browser and you can see these two new cookies.
Cookie Encryption
By default, cookies generated by the Laravel framework are encrypted and signed to prevent them from being tampered with on the client side. If you want a specific subset of cookies to be unencrypted when generated, you can exclude these cookies through the $except attribute provided by the middleware App\Http\Middleware\EncryptCookies in the app/Http/Middleware directory.
/** * 不需要被加密的cookies名称 * * @var array */ protected $except = [ 'cookie_name', ];
Redirect
The redirect response is an instance of the Illuminate\Http\RedirectResponse class and contains the necessary header information to redirect the user to another URL. There are many ways to generate RedirectResponse instances, the simplest way is to use the global helper function redirect.
Route::get('dashboard', function () { return redirect('home/dashboard'); });
Sometimes you want to redirect the user to the location of the previous request. For example, after the form is submitted and the verification fails, you can use the auxiliary function back to return to the previous URL (because this function uses Session, before using this method, ensure that the relevant route is located in the web middleware group or Session middleware is applied).
Route::post('user/profile', function () { // 验证请求... return back()->withInput(); });
Redirect to a named route
If you call the redirect method without parameters, an Illuminate\Routing\Redirector instance will be returned, and then you can use all methods on the Redirector instance.
For example, to generate a RedirectResponse to a named route, you can use the route method.
return redirect()->route('login');
If there are parameters in the route, you can pass it as the second parameter to the route method:
// For a route with the following URI: profile/{id} return redirect()->route('profile', ['id'=>1]);
Populate the route parameters through the Eloquent model
If you want to redirect to Routes with ID parameters (Eloquent model binding) can pass the model itself, and the ID will be automatically parsed.
return redirect()->route('profile', [$user]);
If you want to customize the default parameter name in this routing parameter (the default is id), you need to override the getRouteKey method on the model instance.
/** * Get the value of the model's route key. * * @return mixed */ public function getRouteKey() { return $this->slug; }
Redirect to controller method
You can also generate a method that redirects to the controller, just pass the controller and method name to the action method. Remember, you don't need to specify the full namespace of the controller because Laravel's RouteServiceProvider will automatically set the default controller namespace.
return redirect()->action('HomeController@index');
Like the route method, if the controller route requires parameters, you can pass the parameters as the second parameter to the action method.
return redirect()->action('UserController@profile', ['id'=>1]);
Redirecting with one-time Session data
Redirecting to a new URL and storing the data in the one-time Session is usually done at the same time. For convenience, you can create a RedirectResponse The instance then stores the data into the Session in the same method chain, which is particularly convenient when storing state information after an action.
Route::post('user/profile', function () { // 更新用户属性... return redirect('dashboard')->with('status', 'Profile updated!'); });
用户重定向到新页面之后,你可以从 Session 中取出并显示这些一次性信息,使用 Blade 语法实现如下:
@if (session('status')) <p class="alert alert-success"> {{ session('status') }} </p> @endif
注:这个一次性体现在第一次从 Session 取出数据之后,这些数据就会被销毁,不复存在。
其它响应类型
上面我们讲了 Response 和 RedirectResponse 两种响应类型,我们还可以通过辅助函数 response 很方便地生成其他类型的响应实例,当无参数调用 response 时会返回 Illuminate\Contracts\Routing\ResponseFactory 契约的一个实现,该契约提供了一些有用的方法来生成各种响应,如视图响应、JSON 响应、文件下载、流响应等等。
视图响应
如果你需要控制响应状态和响应头,并且还需要返回一个视图作为响应内容,可以使用 view 方法。
return response() ->view('hello', $data, 200) ->header('Content-Type', $type);
当然,如果你不需要传递自定义的 HTTP 状态码和头信息,只需要简单使用全局辅助函数 view 即可。
Route::get('view/response', function() { return view('hello'); });
注:视图响应的视图文件必须存在,视图文件位于 resources/views 目录中。
JSON响应
json 方法会自动将 Content-Type 头设置为 application/json,并使用 PHP 函数 json_encode 方法将给定数组转化为 JSON 格式的数据。
return response()->json([ 'name' => 'Abigail', 'state' => 'CA' ]);
如果你想要创建一个 JSONP 响应,可以在 json 方法之后调用 withCallback 方法。
return response() ->json(['name' => 'Abigail', 'state' => 'CA']) ->withCallback($request->input('callback'));
或者直接使用 jsonp 方法。
return response() ->jsonp($request->input('callback'), ['name' => 'Abigail', 'state' => 'CA']);
文件下载
download 方法用于生成强制用户浏览器下载给定路径文件的响应。download 方法接受文件名作为第二个参数,该参数决定用户下载文件的显示名称,你还可以将 HTTP 头信息作为第三个参数传递到该方法。
return response()->download($pathToFile); return response()->download($pathToFile, $name, $headers); return response()->download($pathToFile)->deleteFileAfterSend(true);
注:管理文件下载的 Symfony HttpFoundation 类要求被下载文件有一个 ASCII 文件名,这意味着被下载文件名不能是中文。
Route::get('download/response', function() { return response()->download(storage_path('app/photo/test.jpg'), '测试图片.jpg'); });
文件响应
file 方法可用于直接在用户浏览器显示文件,例如图片或 PDF,而不需要下载,该方法接收文件路径作为第一个参数,头信息数组作为第二个参数。
return response()->file($pathToFile); return response()->file($pathToFile, $headers);
响应宏
如果你想要定义一个自定义的可以在多个路由和控制器中复用的响应,可以使用 Response 门面上的 macro 方法。
例如,在某个服务提供者的 boot 方法中编写代码如下:
<?php namespace App\Providers; use Illuminate\Support\Facades\Response; use Illuminate\Support\ServiceProvider; class ResponseMacroServiceProvider extends ServiceProvider { /** * Perform post-registration booting of services. * * @return void */ public function boot() { Response::macro('caps', function ($value) { return Response::make(strtoupper($value)); }); } }
macro 方法接收响应名称作为第一个参数,闭包函数作为第二个参数,响应宏的闭包在 ResponseFactory 实现类或辅助函数 response 中调用宏名称的时候被执行。
Route::get('macro/response', function() { return response()->caps('test'); });
在浏览器中访问 http://www.adm.devp/macro/response ,输出入下:
TEST
相关推荐:
The above is the detailed content of How to create response in Laravel 5.5? Introduction to creating responses (code). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

RESTAPI design principles include resource definition, URI design, HTTP method usage, status code usage, version control, and HATEOAS. 1. Resources should be represented by nouns and maintained at a hierarchy. 2. HTTP methods should conform to their semantics, such as GET is used to obtain resources. 3. The status code should be used correctly, such as 404 means that the resource does not exist. 4. Version control can be implemented through URI or header. 5. HATEOAS boots client operations through links in response.

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

The main function of anonymous classes in PHP is to create one-time objects. 1. Anonymous classes allow classes without names to be directly defined in the code, which is suitable for temporary requirements. 2. They can inherit classes or implement interfaces to increase flexibility. 3. Pay attention to performance and code readability when using it, and avoid repeatedly defining the same anonymous classes.

In PHP, the difference between include, require, include_once, require_once is: 1) include generates a warning and continues to execute, 2) require generates a fatal error and stops execution, 3) include_once and require_once prevent repeated inclusions. The choice of these functions depends on the importance of the file and whether it is necessary to prevent duplicate inclusion. Rational use can improve the readability and maintainability of the code.

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.
