Data is not converted into array when with the DB facade. #53658
-
Laravel Version11.33.2 PHP Version8.2.25 Database Driver & VersionMariaDB ver. 10.11.10 DescriptionHello, With Model// Using model
dump(Project::all()->toArray());
// Using DB facade
dump(DB::table('projects')->get()->toArray()); With DB Facade
Steps To ReproduceTo make comparisons, I had to display this data in the class that extends Console. /**
* Execute the console command.
*/
public function handle(): int
{
// Using model
dump(Project::all()->toArray());
// Using DB facade
dump(DB::table('projects')->get()->toArray());
return Command::SUCCESS;
} This doesn't cause bugs, but rather inconsistencies. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
That is by design. When you call When you query your DBMS through Eloquent, the result set is hydrated into Eloquent models. Those instances implement the When you query your DBMS through the DB façade, the result set is not changed, and by default each record will be an instance of PHP's built-in So, when the collection iterates over these records, it cannot ask them for their array representation. If you need, for some reason, to convert those records to an array, you can try this: dump(DB::table('projects')->get()->map(fn ($record) => (array) $record)->toArray()); The |
Beta Was this translation helpful? Give feedback.
That is by design.
When you call
Collection@toArray()
, the collection instance iterates over its elements and checks if they implement theIlluminate\Support\Traits\Arrayable
interface. If so, it calls that element'stoArray()
method.When you query your DBMS through Eloquent, the result set is hydrated into Eloquent models. Those instances implement the
Illuminate\Support\Traits\Arrayable
, and thus know how to convert themselves into arrays when needed.When you query your DBMS through the DB façade, the result set is not changed, and by default each record will be an instance of PHP's built-in
\stdClass
, and as such, those do not implement any of Laravel's interfaces.So, when the colle…