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

Make Laravel API always return JSON formatted responses

藏色散人
藏色散人forward
2020-04-11 11:53:295584browse

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;
    }
}

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()
);

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!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete