Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

JadoJodo's avatar

Is there a way to return a model from Eloquent builder statement?

I'm working w/ Dingo/Fractal and have an Eloquent model collection that I need to pass into my transformer. Based on URL params, I need to in/exclude joins in my Eloquent query. I start off w/ something like this:

$myModel = Model::

In this part I run into my first issue: Since I know I might be doing a join, I can't call a where (yet, as far as I know) on the Model:: and don't know what else to include (I've tried Model::select).

The solution is to use the Query Builder: $myModel = DB::table('model');

The problem with this is it returns an Array, instead of a Collection and the transformer is expecting a collection of Model's. What's the best option here? Is there something I'm missing? I did also try calling collect($myModel), but it returns a collection of StdClass, instead of Model.

// Full Query Example

$myModel = Model::select('model.id', 'model.name');
if ($request->has('example_param') {
    $myModel->join('example_join_table AS ejt', 'model.id', '=', 'ejt.model_id')
}

$myModel->where('deleted', 0)->get()
0 likes
7 replies
ahuggins's avatar

Model::find($id);

That will find the row by the id for whichever Model you are trying to use. It will return an instance of the Model.

Is that what you are looking for?

1 like
JadoJodo's avatar

@ahuggins Unfortunately, no. In this case, I don't know the Ids of the items I need.

ahuggins's avatar

$myModel->where('deleted', 0)->get()

That should return an instance of Collection. And the example looks right to me.

ahuggins's avatar

Also, you should be able to call where anywhere in the chain, as long as it is before either first(), get(), or all()...each of those functions tell Eloquent to actually build the query and then execute it.

ahuggins's avatar

Another thing I thought...

I would probably do this:

$myModel = Model::select('model.id', 'model.name')->where('deleted', 0)->get();

Then define a relationship on the Model:

class Model {
    public function exampleJoinTable() {
        return $this->hasMany(ExampleJoin::class);
    }
}

Then wherever you need to access the example join table you could do:

if ($request->has('example_param') {
    $myModel->exampleJoinTable;
}

This way the Join is handled by Eloquent Relationships...and with the condition, would only be executed if needed. Or you could eager load it.

It does depend on how exactly you need to access the data and if it makes sense, which I can't quite gather from the information provided.

Please or to participate in this conversation.