Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel JSON response without backslashes

Tags:

json

php

laravel

I am using AJAX post data to my controller.

PHP Code:

return response()->json($request->root() . '/summer-uploads/' . $store);

It returns:

"http:\/\/domain.test\/summer-uploads\/summer-uploads\/PGARvUyeXiAbbTOc90b6HGXXf9ZHmqehOA5f25pE.jpeg"

As you can see it's adding backslashes, some kind of escaping. How can i remove it, so it would be looking like this:

"http://domain.test/summer-uploads/summer-uploads/PGARvUyeXiAbbTOc90b6HGXXf9ZHmqehOA5f25pE.jpeg"

like image 512
Alexander Kim Avatar asked Jun 23 '18 06:06

Alexander Kim


1 Answers

The docs does not show all the arguments to the json method.

But they are tucked away in the source.

JsonResponse->__construct():

/**
 * Constructor.
 *
 * @param  mixed  $data
 * @param  int    $status
 * @param  array  $headers
 * @param  int    $options
 * @return void
 */
 public function __construct($data = null, $status = 200, $headers = [], $options = 0)
 {
     //...
 }

The options parameter would be the json_encode() parameters.

So for example, pretty print and unescaped slashes:

response()->json(..., 200, [], JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT);
like image 177
Lawrence Cherone Avatar answered Nov 09 '22 02:11

Lawrence Cherone