skip to Main Content

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


  1. 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 use firstWhere(), so that it would be

    $lastWeek = ModelA::firstWhere('name', $name)
       ->model_b;
    
    Login or Signup to reply.
  2. You can do like this.

    $lastWeek = ModelA::where('name','=',$name)
        ->with('model_b')
        ->get();
    $lastWeek = $lastWeek->model_b;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search