Laravel eloquent issue: Method does not exist

14,664
$clients = Company::where('guid',$guid);

This returns the Builder class, so when you then add ->clients() it will give you error because the builder class does not have the clients method, your model does.

The correct code would be..

$clients = Company::with('clients')->where('guid',$guid)->get();

PS. Don't use ->all() unless it's something like $companies = Company::all()

Share:
14,664
Ilan Finkel
Author by

Ilan Finkel

Updated on June 28, 2022

Comments

  • Ilan Finkel
    Ilan Finkel over 1 year

    I have 2 tables, Clients and Companies each Company has many clients and each client has one company

    this is my models:

    class Client extends Model
    {
        public function company(){
            return $this->hasOne('App\Company');
        }
    }
    
    class Company extends Model
    {
        public function clients(){
            return $this->hasMany('App\Client');
        }
    }
    

    I'm trying to get a list of all the clients of a company and this is what I tried to do:

    $clients = Company::where('guid',$guid)->clients()->all();
    

    I'm getting this error:

    BadMethodCallException in Macroable.php line 74:
    Method clients does not exist.
    

    thank you for your help!