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

不言
Release: 2023-04-03 12:28:01
Original
1674 people have browsed it

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.

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',
];
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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template