HTTP Responses

JSON Responses

The json method will automatically set the Content-Type header to application/json, as well as convert the given array to JSON using the json_encode PHP function:

Response::json(["name" => "Hassan"]);

Attaching Headers To Responses

Keep in mind that most response methods are chainable, allowing for the fluent construction of response instances. For example, you may use the header method to add a series of headers to the response before sending it back to the user:

// Add header
Response::header("X-Header-One", 'Header Value');

// Add headers by array
Response::headers(['X-Header-One'=>'Header Value-One', 'X-Header-Two'=>'Header Value-Two']);

File Responses

The file method may be used to display a file, such as an image or PDF, directly in the user's browser instead of initiating a download. This method accepts the path to the file as its first argument:

return response()->file("public/image.jpg");

Last updated