Daniel
Daniel

Reputation: 205

Generate object array with values from Database

Suppose I have this table:

id    |    product_item    |    head_count
1     |         400        |        2
2     |         401        |        5

desired output:

[
   {"product_item": 400,"head_count": 2},
   {"product_item": 401,"head_count": 5}
]

How do I make this desired output using Laravel or Eloquent?

Upvotes: 0

Views: 53

Answers (4)

juanvqz
juanvqz

Reputation: 11

Try this:

$products = App\Product::select('product_item', 'head_count')->get()->toArray();

or if is one:

$product = App\Product::select('product_item', 'head_count')->first()->toArray();

or

    $product = App\Product::get(['product_item', 'head_count'])->toArray();

and return:

[ {Producto}, {Producto}]

Upvotes: 0

hitesh makodiya
hitesh makodiya

Reputation: 437

Follow bellow step  
(1) declare in your controller **use DB**  

(2) write Query:  
$product = DB::table('tablename')->select('col1','col2')->get(); 

(3)dd($product); OR print_r($product);  

You got the result in $product  

echo json_encode($product); 

OR if you are load your view then,  
return view('VIEW_NAME',compact('product'));  

OR return like this and got the result on your view file.

return response()->json($product);

I hope its help.

Upvotes: 3

Shreeraj
Shreeraj

Reputation: 767

You can try this way :

$products = Products::all();

$data = [];

foreach($products as $value)
{
   $temp = [
      'product_item' => $value->product_item,
      'head_count' => $value->head_count
   ];

   array_push($data,$temp);
}

return $data;

OR

return response()->json($data);

You will get required output in $data

Upvotes: 0

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

Create a Model Product (for example) for your table, then select the data like :

Product::get(["product_item","head_count"]);

That will return a Collection of Product objects.

[ 
    {
        "product_item": 400,
        "head_count": 2
    },
    {
        "product_item": 401,
        "head_count": 5
    }
]

NOTE: If your table name is products you don't need to add the name of the table to your model since the Product is the singular of your table name, what means you're following conventions and laravel will detect the related table automatically.

Else you need to add the table name at the top of your Model Product.php like :

class Product extends Model
{

    protected $table = 'products';

}

Upvotes: 0

Related Questions