Convert Laravel Query builder to Eloquent builder

2020-07-23 08:05发布

问题:

Because get() function of Query builder returns an array while I need A collection, is there a way to convert Laravel Query Builder to Eloquent Builder?

$query_builder = DB::table('table1');

// different than
$eloquent_builder = Table1Model::select()

回答1:

Laravel ships with a collect helper to convert an array to a collection:

$collection = collect(DB::table('table1')->get());

There's a proposal on Github to have the next version of Laravel return collection instances from the query builder's get method.