When creating a query using the syntax DB::table(\'foo\')
, it creates a generic class (stdClass). Is there any way to cast the resulting rows to a specific class?>
Laravel 5.8
In the class you want to cast to (YourClass
in this example) to you'll need constructor like this:
/**
* Use to initialize fields from DB query like:
* $query->mapInto(YourClass::class)
*
* YourClass constructor.
* @param \stdClass $data
*/
public function __construct(\stdClass $data)
{
foreach ($data as $key => $value) {
$this->$key = $value;
}
}
Then in your query:
$result = $query
->get()
->mapInto(YourClass::class);
$result will now contain a collection of YourClass
instances with fields loaded from the query.