Table of Contents
Create response" >Create response
String & Array
Response object
Add response header
Adding Cookies to Responses
Cookie Encryption
Redirect" >Redirect
Redirect to a named route
Populate the route parameters through the Eloquent model
Redirect to controller method
Redirecting with one-time Session data
其它响应类型" >其它响应类型
视图响应
JSON响应
文件下载
文件响应
响应宏
Home Backend Development PHP Tutorial How to create response in Laravel 5.5? Introduction to creating responses (code)

How to create response in Laravel 5.5? Introduction to creating responses (code)

Jul 25, 2018 pm 05:27 PM

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';
});
Copy after login

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];
});
Copy after login

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');
});
Copy after login

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');
Copy after login

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',
    ]);
Copy after login

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);
Copy after login

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)
Copy after login

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');
});
Copy after login

Visit http://www.adm.devp/cookie/response in your browser and you can see these two new cookies.

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',
];
Copy after login

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');
});
Copy after login

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();
});
Copy after login

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');
Copy after 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]);
Copy after login

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]);
Copy after login

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;
}
Copy after login

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');
Copy after login

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]);
Copy after login

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!');
});
Copy after login

用户重定向到新页面之后,你可以从 Session 中取出并显示这些一次性信息,使用 Blade 语法实现如下:

@if (session('status'))
    <p class="alert alert-success">
        {{ session(&#39;status&#39;) }}
    </p>
@endif
Copy after login

注:这个一次性体现在第一次从 Session 取出数据之后,这些数据就会被销毁,不复存在。

其它响应类型

上面我们讲了 Response 和 RedirectResponse 两种响应类型,我们还可以通过辅助函数 response 很方便地生成其他类型的响应实例,当无参数调用 response 时会返回 Illuminate\Contracts\Routing\ResponseFactory 契约的一个实现,该契约提供了一些有用的方法来生成各种响应,如视图响应、JSON 响应、文件下载、流响应等等。

视图响应

如果你需要控制响应状态和响应头,并且还需要返回一个视图作为响应内容,可以使用 view 方法。

return response()
        ->view(&#39;hello&#39;, $data, 200)
        ->header(&#39;Content-Type&#39;, $type);
Copy after login

当然,如果你不需要传递自定义的 HTTP 状态码和头信息,只需要简单使用全局辅助函数 view 即可。

Route::get(&#39;view/response&#39;, function() {
   return view(&#39;hello&#39;);
});
Copy after login

注:视图响应的视图文件必须存在,视图文件位于 resources/views 目录中。

JSON响应

json 方法会自动将 Content-Type 头设置为 application/json,并使用 PHP 函数 json_encode 方法将给定数组转化为 JSON 格式的数据。

return response()->json([
        &#39;name&#39; => &#39;Abigail&#39;, 
        &#39;state&#39; => &#39;CA&#39;
]);
Copy after login

如果你想要创建一个 JSONP 响应,可以在 json 方法之后调用 withCallback 方法。

return response()
        ->json([&#39;name&#39; => &#39;Abigail&#39;, &#39;state&#39; => &#39;CA&#39;])
        ->withCallback($request->input(&#39;callback&#39;));
Copy after login

或者直接使用 jsonp 方法。

return response()
        ->jsonp($request->input(&#39;callback&#39;), [&#39;name&#39; => &#39;Abigail&#39;, &#39;state&#39; => &#39;CA&#39;]);
Copy after login

文件下载

download 方法用于生成强制用户浏览器下载给定路径文件的响应。download 方法接受文件名作为第二个参数,该参数决定用户下载文件的显示名称,你还可以将 HTTP 头信息作为第三个参数传递到该方法。

return response()->download($pathToFile);
return response()->download($pathToFile, $name, $headers);
return response()->download($pathToFile)->deleteFileAfterSend(true);
Copy after login

注:管理文件下载的 Symfony HttpFoundation 类要求被下载文件有一个 ASCII 文件名,这意味着被下载文件名不能是中文。

Route::get(&#39;download/response&#39;, function() {
    return response()->download(storage_path(&#39;app/photo/test.jpg&#39;), &#39;测试图片.jpg&#39;);
});
Copy after login

文件响应

file 方法可用于直接在用户浏览器显示文件,例如图片或 PDF,而不需要下载,该方法接收文件路径作为第一个参数,头信息数组作为第二个参数。

return response()->file($pathToFile);
return response()->file($pathToFile, $headers);
Copy after login

响应宏

如果你想要定义一个自定义的可以在多个路由和控制器中复用的响应,可以使用 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(&#39;caps&#39;, function ($value) {
            return Response::make(strtoupper($value));
        });
    }
}
Copy after login

macro 方法接收响应名称作为第一个参数,闭包函数作为第二个参数,响应宏的闭包在 ResponseFactory 实现类或辅助函数 response 中调用宏名称的时候被执行。

Route::get(&#39;macro/response&#39;, function() {
    return response()->caps(&#39;test&#39;);
});
Copy after login

在浏览器中访问 http://www.adm.devp/macro/response ,输出入下:

TEST
Copy after login

相关推荐:

如何实现Laravel 5.5可响应接口

Laravel5.2博客实战视频教程

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

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.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What is REST API design principles? What is REST API design principles? Apr 04, 2025 am 12:01 AM

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.

How do you handle exceptions effectively in PHP (try, catch, finally, throw)? How do you handle exceptions effectively in PHP (try, catch, finally, throw)? Apr 05, 2025 am 12:03 AM

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.

What are anonymous classes in PHP and when might you use them? What are anonymous classes in PHP and when might you use them? Apr 04, 2025 am 12:02 AM

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.

See all articles