Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent / fluent

Tags:

laravel

When fetching all rows from an Eloquent Model :

$pin = Pin::all();

I get an array that looks like:

array(2) {
  [0]=>
  object(Pin)#36 (5) {
    ["attributes"]=>
    array(9) {
      ["id"]=>
      string(1) "2"
      ["creator"]=>
      string(1) "1"
    ["original"]=>
    array(9) {
      ["id"]=>
      string(1) "2"
      ["creator"]=>
      string(1) "1"
    }
    ["relationships"]=>
    array(0) {
    }
    ["exists"]=>
    bool(true)
    ["includes"]=>
    array(0) {
    }
  }
}

As when I use Fluent instead:

$pin = DB::table('pins')->get();

I get as a plain array without the "Attribute", "Orginial", "realtionships" .. indexes.

How can I use Eloquent so that it returns a Plain Array like FLuent does?

like image 289
silkAdmin Avatar asked Oct 07 '12 21:10

silkAdmin


People also ask

What is Laravel fluent?

Fluent is a utility class provided by @laravelphp that lets us handle data fluently. Out of the box it can be turned into an array or JSON, it can act as an array and it's serializable as a JSON.

What is Laravel eloquent?

Eloquent is an object relational mapper (ORM) that is included by default within the Laravel framework. An ORM is software that facilitates handling database records by representing data as objects, working as a layer of abstraction on top of the database engine used to store an application's data.

Why we use eloquent in Laravel?

The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table.

What is fluent query builder in Laravel?

The Fluent Query Builder is Laravel's powerful fluent interface for building SQL queries and working with your database. All queries use prepared statements and are protected against SQL injection. You can begin a fluent query using the table method on the DB class.


1 Answers

Its very simple.

$pins = Pin::get();
foreach($pins as $p){
 $pin[] = $p->to_array();
}

or if you want to send out JSON object, try using

$pins = Pin::all();
return Response::eloquent($pins);

or if you have an Array to be converted to json output than use

return Response::json(array('name' => 'Batman'));
like image 60
Raftalks Avatar answered Oct 14 '22 19:10

Raftalks