Matías Cánepa
Matías Cánepa

Reputation: 5974

get collection of objects in laravel

In a controller, I can do this:

$myentity = MyEntity::findOrFail($id);
$collection = MyEntity::where("field", "=", $myentity->value)->get();

which gives me a collection of MyEntity objects...

dd($collection);
Collection {#331 ▼
  #items: array:11 [▼
    0 => MyEntity {#332 ▶}
    1 => MyEntity {#333 ▶}
    2 => MyEntity {#334 ▶}
    3 => MyEntity {#335 ▶}
    4 => MyEntity {#336 ▶}
    5 => MyEntity {#337 ▶}
    6 => MyEntity {#338 ▶}
    7 => MyEntity {#339 ▶}
    8 => MyEntity {#340 ▶}
    9 => MyEntity {#341 ▶}
    10 => MyEntity {#342 ▶}
  ]
}

I need to implement a method inside the Model class that returns the exact same thing but I'm not making it work properly. I've tried something like this:

public function test()
{
    return = DB::table("entity")->where("field", "=", $this->value)->get();
}

...

$myentity = MyEntity::findOrFail($id);
$collection = $myentity->test();
dd($collection);
Collection {#319 ▼
  #items: array:10 [▼
    0 => {#309 ▶}
    1 => {#322 ▶}
    2 => {#308 ▶}
    3 => {#320 ▶}
    4 => {#324 ▶}
    5 => {#310 ▶}
    6 => {#315 ▶}
    7 => {#321 ▶}
    8 => {#325 ▶}
    9 => {#326 ▶}
  ]
}

How can I get the same result?

Upvotes: 0

Views: 720

Answers (1)

old greg
old greg

Reputation: 897

If you use DB::table, the framework doesn't know what PHP class to cast the results to. If you use MyModel::query()->where('foo', 'bar')->get(), it should automatically create an instance of MyModel for each member of the Collection.

Upvotes: 1

Related Questions