This is my model
class ModelA extends Model
{
use HasFactory;
public function model_b()
{
return $this->hasMany(ModelB::class);
}
}
This query works well.
$lastWeek = ModelA::find(1)
->model_b->get();
When I am using where clause query
$lastWeek = ModelA::where('name','=',$name)
->model_b->get();
It says:
Property [model_b] does not exist on the Eloquent builder instance.
2
Answers
In your first query,
find()
returns the model, so you are able to access the relation. I think the->get()
in that instance doesn’t do anything.In your last query, the
where
clause doesn’t return the model (its returning the eloquent builder) before you try and access its relation. You could usefirstWhere()
, so that it would beYou can do like this.