William Lawn Stewart
William Lawn Stewart

Reputation: 1205

Converting Laravel-4 Eloquent query results to arrays

I'm trying to get my route to insert a new row into the database, and if successful return the record (with its new primary key id) in some JSON. I'm getting the following error:

{
    "error":
    {
        "type":"BadMethodCallException",
        "message":"Call to undefined method Illuminate\\Database\\Query\\Builder::to_array()",
        "file":"\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Query\\Builder.php",
        "line":1418
    }

}

This is my route:

Route::post('/client/create', function()
{
    $client = Client::create(Input::all());
    if($client)
    {
        return json_encode(array('Result' => 'OK', 'Record' => $client->to_array()));
    }
    else
    {
        return json_encode(array('Result' => 'ERROR', 'Message' => 'Error Inserting Record =('));
    }
});

According to the Laravel docs I've read, you're supposed to use ->to_array() to convert your model to an array, and ::create returns an instance of the model if successfully inserted. I've checked the database, and the records are being inserted just fine.

Upvotes: 4

Views: 20548

Answers (3)

Dwight
Dwight

Reputation: 12470

The to_array() method comes from Laravel 3. Use toArray() in Laravel 4.

Upvotes: 3

krissanawat
krissanawat

Reputation: 626

I see question similar you try to return data to jquery jtable and same me

Player::orderBy($sort)->paginate($pagesize)->getCollection();
return Response::view(array('Result'=>'OK','Records'=>$player->toArray()));

for try many hour I found solution getcollection pull instance from object and then solve

Upvotes: 1

Jason Lewis
Jason Lewis

Reputation: 18665

By default if you were to return an Eloquent model directly it would convert the model to it's JSON representation. This is because the __toString magic method on each model returns the model as JSON by using the toJson method.

As such the model implements both the ArrayableInterface and JsonableInterface. That means you can directly call toJson or toArray on a model.

Now you can mark columns as hidden. This means that when a model is converted into it's array or JSON representation some columns are removed (think publicly accessible API, you don't want passwords showing up!). I'm not totally sure but maybe the ID of your model is being hidden.

At the end of the day, all you need to do is return the instance.

return $client;

It'll be converted to JSON for you automatically.

Upvotes: 9

Related Questions