Basaa
Basaa

Reputation: 1685

Return eloquent collection as json format

I'm trying to implement a RESTful api in Laravel, and I for my index I want to return all the tasks as json.

However, when I use

return Response::json(Task::all());

I get an error: "The Response content must be a string or object implementing __toString(), "boolean" given".

I get the same error when I use:

return Task::all();

I thought this was supposed to work? What am I doing wrong?

I double-checked to see if Task::all() actually returns anything, and it does. This code does work in another project, although on another server and maybe another php version?

Someone suggested to use toArray(), but I get the same result. Code:

<?php

class UserController extends BaseController {

    public function index() {
        $users = User::all();
        $userArray = $users->toArray();
        return Response::json($userArray);
    }

}

Upvotes: 3

Views: 2891

Answers (1)

Hassan
Hassan

Reputation: 626

Response::json function is expecting argument 1 to be an array. From the API:

json( string|array $data = array(), integer $status = 200, array $headers = array() )
Return a new JSON response from the application.

So you can't just pass through the results of your find, but instead use the toArray() function and pass that through instead:

$tasks = Task::all();
Response::json($tasks->toArray());

Edit ---

If you're working with a BLOB, then base64_encode it first. See this post.

Example:

base64_encode($user['image']);

Upvotes: 3

Related Questions