How to convert stdclass object to array in laravel 5.8
Today, We will learn how to convert the stdclass object to the array in laravel 5.8. normally we get data from the database that time the laravel return the collection of or object types formatting data. but sometimes we need to object to array formatting data. so we will learn many ways about how to convert the stdclass object to the array.
You can use the toArray method to convert a stdclass object to array. you can see below example.
1 2 3 4 | $data = DB::table('users')->get()->toArray(); echo "<pre>"; print_r($data); echo "</pre>"; |
You can also use json_encode to json_decode convert stdclass object to array.
1 2 3 4 5 | $data = DB::table('users')->get(); $result = json_decode(json_encode($data, true)); echo "<pre>"; print_r($result); echo "</pre>"; |
You can use setFetchMode to convert a stdclass object to array.
1 2 3 4 5 | DB::setFetchMode(PDO::FETCH_ASSOC); $data = DB::table('users')->get(); echo "<pre>"; print_r($data); echo "</pre>"; |
You can change in the database config setting. Doing that setting, All project stdclass object will be converted into the array.
1 2 3 4 5 | // application/config/database.php 'fetch' => PDO::FETCH_CLASS, // to 'fetch' => PDO::FETCH_ASSOC, |
Please follow and like us: