6
votes

When defining an inverse relation in Eloquent, do you have to name your dynamic property the same as your related model?

class Book extends Eloquent {

    public function author()
    {
        return $this->belongsTo('Author');
    }

}

$books = Book::all()
foreach ($books as $book) {
    echo $book->author->firstname;
}

In the above example, do I have to call this method author or can I name it something else? I tried to name it to something else (just out of curiosity) but it then returns null hence the errors "Trying to get property of non-object".

EDIT: I got it to work by passing the foreign key to belongsTo, like this:

class Book extends Eloquent {

    public function daauthor()
    {
        return $this->belongsTo('Author', 'author_id');
    }

}

$book = Book::find(55);
dd($book->daauthor);

Can someone explain why?

1
You can name it whatever you want :). What was the error and function name you tried?Sven van Zoelen
if i change Book::author() to Book::daauthor() and call it like: $book->daauthor, i get null back.skaterdav85
I can rename my eloquent functions to whatever, tried it in my Laravel4 project. The function BelongsTo() does nothing with your function's name. Maybe you overlooked something in your code?Sven van Zoelen
so in theory, changing author() to daauthor() in the Book class and then in the foreach loop using $book0>daauthor should return something? anything else i might be missing?skaterdav85
it turns out you have to pass in the name of the foreign key for it to work. did you have to do that?skaterdav85

1 Answers

4
votes

The method belongsTo tries to determine the attribute which links to the Author model. To accomplish this Laravel uses the function name of the caller.

So in your code Laravel sees the daauthor function and tries to use the attribute daauthor_id in the books table to fully your request. As your books table does not have this attribute it fails.

By setting the $foreignKey on the method you can override the default behaviour:

public function daauthor()
{
    return $this->belongsTo('Author', 'author_id');
}

For more details check out the source code of \Illuminate\Database\Eloquent\Model.