Sergi Hurtado Abad
Sergi Hurtado Abad

Reputation: 9

Special characters generating JSON with Laravel

I'm trying to create an api within laravel. However when it generates the json, it includes those special characters:

image I tried to return nothing at all and it still returns me those characters. I tried putting it in all the codifications possibles and is always the same.

The routes are defined on api.php:

Route::get('/draws',[
    'middleware' => 'cors',
    'uses' => 'DrawController@getDraws'
]);

The Controller function is this:

    public function getDraws(){
    $draws = Draw::all();
    $response = [
        'draws' => $draws
    ];

    $headers = ['Content-Type' => 'application/json; charset=UTF-8'];

    return response()->json($response, 200, $headers);
}

My class Cors is this:

use Closure;

class Cors {

public function handle($request, Closure $next)
{

    header("Access-Control-Allow-Origin: *");

    // ALLOW OPTIONS METHOD
    $headers = [
        'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
        'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'  
    ];
    if($request->getMethod() == "OPTIONS") {
        // The client-side application can set only headers allowed in Access-Control-Allow-Headers
        return Response::make('OK', 200, $headers);
    }

    $response = $next($request);
    foreach($headers as $key => $value)
        $response->header($key, $value);
    return $response;
}

}

the dd($response) returns me this:

array:1 [▼
  "draws" => Collection {#236 ▼
    #items: array:8 [▼
      0 => Draw {#237 ▼
        #connection: "mysql"
        #table: null
        #primaryKey: "id"
        #keyType: "int"
        +incrementing: true
        #with: []
        #withCount: []
        #perPage: 15
        +exists: true
        +wasRecentlyCreated: false
        #attributes: array:4 [▶]
        #original: array:4 [▶]
        #changes: []
        #casts: []
        #dates: []
        #dateFormat: null
        #appends: []
        #dispatchesEvents: []
        #observables: []
        #relations: []
        #touches: []
        +timestamps: true
        #hidden: []
        #visible: []
        #fillable: []
        #guarded: array:1 [▶]
      }
      1 => Draw {#238 ▶}
      2 => Draw {#239 ▶}
      3 => Draw {#240 ▶}
      4 => Draw {#241 ▶}
      5 => Draw {#242 ▶}
      6 => Draw {#243 ▶}
      7 => Draw {#244 ▶}
    ]
  }
]

Upvotes: 0

Views: 1959

Answers (1)

There is no need to do that:

$draws = Draw::all();
$response = [
    'draws' => $draws
];

$headers = ['Content-Type' => 'application/json; charset=UTF-8'];

return response()->json($response, 200, $headers);

You can simple return the collection, that automaticaly will convert to correct json response, try making like this:

return Draw::all()

Upvotes: 1

Related Questions