Sander
Sander

Reputation: 13

Laravel Eloquent relationships hasmany error: Call to undefined method when using on where

I have a question about the hasmany relationship in laravel eloquent. To understand my question, i will share some information about my project . I have a user, workspace and project model. The workspace model has a "has many" relationship with the project model. The project model has a "belongsTo" relationship with the workspace model.

Workspace model:

class Workspace extends Model {
    
use HasFactory;

public function projects(): \Illuminate\Database\Eloquent\Relations\HasMany {
       return $this->hasMany(Project::class);
    }
  }

Project model:

class Project extends Model

{
    use HasFactory;

    public function workspace(){
       return $this->belongsTo(Workspace::class, 'foreign_key');
   }
}

I'm trying to retrieve all workspaces from the logged in user, with the projects belonging to the workspace with the following piece of code in my index function in the workspace controller.

return Workspace::where('user_id', '=', 1)->projects()->get();

When this piece of code runs, i get

BadMethodCallException Call to undefined method Illuminate\Database\Eloquent\Builder::projects()

So my question here is: Why is Laravel giving me a bad method error and how can i retrieve my workspaces with its projects that belong to a certain user?

Upvotes: 0

Views: 1988

Answers (1)

John Lobo
John Lobo

Reputation: 15339

It should be.You can use with method load relationship data

return Workspace::where('user_id', '=', 1)->with('projects')->get();

For better understanding with accept two params

 with($relations, $callback = null)

callbacks help us to write query on relations

with Set the relationships that should be eager loaded.

Upvotes: 2

Related Questions