Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify default parameters for Response::json()

Tags:

php

laravel

Is there any way to specify default parameters for Response::json()? The problem is that, in my case, Response::json($data) returns utf8 and since that I need to specify extra parameters to be able to read it:

$headers = ['Content-type'=> 'application/json; charset=utf-8'];
return Response::json(Course::all(), 200, $headers, JSON_UNESCAPED_UNICODE);

That’s quite tiresome and looks like superfluous …

like image 946
zhekaus Avatar asked Aug 18 '15 12:08

zhekaus


2 Answers

You can create a new method in your (base) controller to set all those headers.

protected function jsonResponse($data) {
    $headers = ['Content-type'=> 'application/json; charset=utf-8'];
    return Response::json($data, 200, $headers, JSON_UNESCAPED_UNICODE);
}

and then return your response like this in your controller route:

return $this->jsonResponse(Course::all());

Or you could create a new UTF8JsonResponse class extending the default Response, setting all the headers in the constructor, and returning that return new UTF8JsonResponse(Course::all()).

like image 186
darthmaim Avatar answered Nov 07 '22 16:11

darthmaim


I know this question is old but here's something that works quite well.

First create your own ResponseFactory class e.g.:

namespace App\Factories;

class ResponseFactory extends \Illuminate\Routing\ResponseFactory {
    public function json($data = [], $status = 200, array $headers = [], $options = 0) {
        // If we haven't passed options manually override the default. 
        // You can always change this to always override the default
        if (func_num_args() < 4) { 
            $options = JSON_UNESCAPED_UNICODE;
        }
        return parent::json($data, $status, $headers, $options);
    }
}

Then in your AppServiceProvider set the container to resolve your ResponseFactory whenever a response factory interface is required:

class AppServiceProvider extends ServiceProvider {

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot() {
        // ... Other things
        $this->app->singleton(ResponseFactory::class, \App\Factories\ResponseFactory::class);
    }

    // Rest of class

}

Now, whenever you call Response::json($variable) your override will run instead of the default. Since your override extends the built-in default response factory everything else should work the same.

like image 34
apokryfos Avatar answered Nov 07 '22 15:11

apokryfos