Question

I have some related models:

Client
id, name, user_id ++

Projects
id, title, client_id, user_id ++

Users
id, name ++

A client belongs to a user, and a client has many projects, and a project belongs to a client and a user.

When I try the following query to get the projects for a client, I get an error saying

Method [projects] is not defined on the Query class.

What does this mean?

I've tried the following queries:

Client::find(2)->where('user_id', '=', Auth::user()->id)->projects() // Throws error
Client::where('id', '=', 2)->where('user_id', '=', Auth::user()->id)->projects() // Also throwing an error

The following query works perfectly:

Client::find(2)->projects

My models are simple and looks like this:

<?php

class Client extends Eloquent
{
    public static $timestamps = TRUE;

    public function user()
    {
        return $this->belongs_to('User');
    }

    public function projects()
    {
        return $this->has_many('Project');
    }
}

class Project extends Eloquent
{
    public static $timestamps = TRUE;

    public function client()
    {
        return $this->belongs_to('Client');
    }

    public function user()
    {
        return $this->belongs_to('User');
    }
}

class User extends Eloquent
{
    public static $timestamps = TRUE;

    public function clients()
    {
        return $this->has_many('Client');
    }

    public function projects()
    {
        return $this->has_many('Project');
    }
}

Why won't it work when I use where clauses? It works when I don't use where clauses, but I need to filter projects and clients on user_id as well. (My plan is to allow multiple users connected to a company to see all their projects and clients.)

Was it helpful?

Solution

You are actually not retrieving anything from the query, just add first() or add get() then loop and call your projects().

Should work like this:

Client::where('id', '=', 2)->where('user_id', '=', Auth::user()->id)->first()->projects()

And according to your comment, it should work too for single row:

Client::find(2)->projects()->where('user_id', '=', Auth::user()->id);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top