Ying
Ying

Reputation: 1422

Naming convention for Eloquent relation method

I'm confused about how I should name my Method in a model. I know in Laravel Eloquent documentation it supposes to be Plural but in some case, it gives me errors. for example, i have this query:

$posts = Post::with(['comments','user', 'tag'])->findOrFail($id);

and then i print the results like this:

    echo "<h1>".$posts->title.'</h1>';
    echo "<h2> created by: ".$posts->user->name.'</h2>';
    echo "<p>".$posts->body."</p>";
    //echo $posts->comments;
    echo '<h3>Komentar :</h3>';
    foreach ($posts->comments as $comment) {
        echo $comment->body.'<br>';
    }
    echo '<h3>Tags :</h3>';
    foreach ($posts->tags as $tag) {
        echo '<a href="/tag/'. $tag->id .'">'.$tag->name.'</a><br>';
    }

it give me an errors:

"Call to undefined relationship [tag] on model [App\Post]."

but when i change my "tags" function inside Post Model into just "tag" the problems are gone. so can anybody explain what is it any name convention for this? thanks.

for more information here's my post model:

class Post extends Model
{
    /**
     * Get the comments for the blog post.
     */
    public function comments()
    {
        return $this->hasMany('App\Comment');
    }

    public function user(){
        return $this->belongsTo('App\User');
    }

    public function tags(){
        return $this->belongsToMany('App\Tag');
    }
}

Upvotes: 0

Views: 1105

Answers (1)

Tudor
Tudor

Reputation: 1898

It seems you are using just singular here $posts = Post::with(['comments','user', 'tag'])->findOrFail($id);

And you are using plural here foreach ($posts->tags as $tag) {

Try using plural in your first example as well: Post::with(['comments','user', 'tags'])

Upvotes: 2

Related Questions