0

I look at many search results with this trouble but i can`t get it to work.

The User Model:

<?php namespace Module\Core\Models;

class User extends Model {

(...)

protected function Person() {
    return $this->belongsTo( 'Module\Core\Models\Person', 'person_id' );
}

(...)

And the Person Model:

<?php namespace Module\Core\Models;

class Person extends Model {

(...)

protected function User(){
    return $this->hasOne('Module\Core\Models\User', 'person_id');
}

(...)

Now, if i use User::find(1)->Person->first_name its work. I can get the Persons relations from the User Model.

But.. User::with('Person')->get() fails with a Call to undefined method Illuminate\Database\Query\Builder::Person()

What im doing wrong? i need a collection of all the users with their Person information.

Cheycron Blaine
  • 39
  • 1
  • 2
  • 9

1 Answers1

1

You have to declare the relationship methods as public.

Why is that? Let's take a look at the with() method:

public static function with($relations)
{
    if (is_string($relations)) $relations = func_get_args();

    $instance = new static;

    return $instance->newQuery()->with($relations);
}

Since the method is called from a static context it can't just call $this->Person(). Instead it creates a new instance of the model and creates a query builder instance and calls with on that and so on. In the end the relationship method has to be accessible from outside the model. That's why the visibility needs to be public.

lukasgeiter
  • 147,337
  • 26
  • 332
  • 270