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

In this post we will give you information about How to convert Collections object to array or json in Laravel PHP Framework. Hear we will give you detail about How to convert Collections object to array or json in Laravel PHP FrameworkAnd how to use it also give you demo for it if it is necessary.

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= AppProduct::all();
  2. return$products->toArray();
$products = AppProduct::all();return $products->toArray();

Convert eloquent model to json :

  1. $product= AppProduct::find(1);
  2. return$product->toJson();
$product = AppProduct::find(1);return $product->toJson();

Cast Model to String

  1. $product= AppProduct::find(1);
  2. return(string)$product;
$product = AppProduct::find(1);return (string) $product;
Many times in Laravel application you need this code to convert collections to array.

Hope this code and post will helped you for implement How to convert Collections object to array or json in Laravel PHP Framework. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

9  +  1  =  

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US