Reputation: 133
If i try to return a JSON-String by using return response()->json($categorie);
i get an empty response.
If i replace the return
for echo
, so i will get
HTTP/1.0 200 OK Cache-Control: no-cache Content-Type: application/json {"id":5,"name":"blah","parent":4,"visible":"yes","position":0,"created_at":"2016-06-29 15:23:25","updated_at":"2016-06-29 15:23:25"}
as Browser output.
I'm using Laravel 5.2. Here's the complete code:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Categories;
class ApiController extends Controller
{
public static function categorieGetById($id) {
$categorie = Categories::find($id);
echo response()->json($categorie);
// return response()->json($categorie);
}
}
UPDATE: the controller returns nothing. every return
produce an empty output.
why?
Upvotes: 3
Views: 4933
Reputation: 6539
You should use toJson() method.
$categorie = Categories::find($id)->toJson();
echo $categorie; // your json output
return $categorie; // same json output
The toJson method converts the collection into JSON.
in your current code,
$categorie = Categories::find($id);
return response()->json($categorie); // your json output with return
Note:- You must write return
here.
In above code if you write echo,
echo response()->json($categorie);
then it will show
HTTP/1.0 200 OK Cache-Control: no-cache Content-Type: application/json {"id":5,"name":"blah","parent":4,"visible":"yes","position":0,"created_at":"2016-06-29 15:23:25","updated_at":"2016-06-29 15:23:25"}
Upvotes: 1
Reputation: 301
A qoute from http://laravel-tricks.com/tricks/return-json-response:
In the official docs : http://laravel.com/docs/responses#special-responses, need to do Response::json(...) to create json response. Actually, if the returned value is an array or instance of arrayableinterface or jsonableinterface such as eloquent model, you could just return it, it'll be a json, magically.
Upvotes: 0