Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 825
William Lawn Stewart Avatar asked Dec 11 '22 15:12

William Lawn Stewart


1 Answers

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.

like image 173
Jason Lewis Avatar answered Feb 11 '23 22:02

Jason Lewis