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 …
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())
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With