Home > PHP Framework > Laravel > Make Laravel API always return JSON formatted responses

Make Laravel API always return JSON formatted responses

藏色散人
Release: 2020-04-11 11:53:29
forward
5749 people have browsed it

Make Laravel API always return JSON formatted responses

When you're writing a Laravel application that serves your API entirely, you want all responses to be in JSON format, rather than, for example, authorization errors redirecting to /home or /login , the final redirection will become the view of InvalidArgumentException: Route [login] is not defined.

Recommended tutorial: "laravel tutorial"

The following simple solution can make your Laravel application respond in JSON format first.

First step, write BaseRequest

First we need to build a BaseRequest to rewrite Illuminate\Http\Request and modify it to use JSON response by default:

app/Http/Requests/BaseRequest.php

<?php
namespace App\Http\Requests;
use Illuminate\Http\Request;
class BaseRequest extends Request
{
    public function expectsJson()
    {
        return true;
    }
    public function wantsJson()
    {
        return true;
    }
}
Copy after login

The second step is to replace BaseRequest

In the public/index.php file, replace \Illumiate\ Replace Http\Request with our BaseRequest, as follows:

$response = $kernel->handle(
    $request = \App\Http\Requests\BaseRequest::capture()
);
Copy after login

Done!

Now all responses are application/json, including errors and exceptions.

From the community https://learnku.com/laravel/wikis/16069

The above is the detailed content of Make Laravel API always return JSON formatted responses. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
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