0

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?

4 Answers 4

3
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.
Sign up to request clarification or add additional context in comments.

Comments

0

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';

}

Comments

0

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

Comments

0

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}]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.