How to convert Collections object to array or json in Laravel PHP Framework

How to convert Collections object to array or json in Laravel PHP Framework

You can convert collections in array and convert eloquent model to json.

Sometime you need array instead of collections then you can use toArray method to convert collections to array.If you want to convert model to json then use toJson method.

You can also cast a collection or model to string.

here is sample code to convert collections object to array in Laravel.

  1. $products = App\Product::all();
  2. return $products->toArray();
Convert eloquent model to json :

  1. $product = App\Product::find(1);
  2. return $product->toJson();
Cast Model to String

  1. $product = App\Product::find(1);
  2. return (string) $product;

Phone: (+91) 8800417876
Noida, 201301