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 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.

$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.

$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.

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.

// application/config/database.php

'fetch' => PDO::FETCH_CLASS,
 // to
'fetch' => PDO::FETCH_ASSOC,