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.
- $products= AppProduct::all();
- return$products->toArray();
$products = AppProduct::all();return $products->toArray();
Convert eloquent model to json :
- $product= AppProduct::find(1);
- return$product->toJson();
$product = AppProduct::find(1);return $product->toJson();
Cast Model to String
- $product= AppProduct::find(1);
- return(string)$product;
$product = AppProduct::find(1);return (string) $product;
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