0

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?

1
  • you can't use query builder, that won't give you models ... you have to use the model to do the query, just like you are doing outside the model Commented Sep 27, 2020 at 16:57

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

you don't need to call query() ...MyModel::where(....) creates the eloquent builder instance dynamically

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.