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?>
You cannot type cast it this way.
You can build change Your Foo class to get handle of object and work with it.
class Foo {
private $object = null;
public function __construct(stdClass $object) {
$this->object = $object;
}
public function __get($property) {
if (property_exists($this->object, $property)) {
return $this->object->$property;
}
}
public function __set($property, $value) {
if (property_exists($this->object, $property)) {
$this->object->$property = $value;
}
return $this;
}
public static function make(stdClass $object) {
return new self($object);
}
public static function makeCollection(array $collection) {
foreach($collection AS $key => $Item) {
$collection[$key] = self::make($Item);
}
return $collection;
}
}
$result = DB::table('foo')->get();
$converted = Foo::makeCollection($result);