Ad

Laravel One To Many Relationship

- 1 answer

I have an Author model and Blog model.

I also set up a table with the author_id and blog_id. The table is called "author_blog".

Below is how I am defining my relationships:

Author Model:

public function blogs()
{
   return $this->hasMany('App\Blog', 'author_id');
}

Blog Model:

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

In my view I am trying to do $blog->author->first_name. The first name is a column on the Authors table.

I keep getting

trying to get property on non-object.

Any ideas?

UPDATE:

I have removed the intermediate table and instead put an "author_id" on my blogs table and shortened it as such.

Author Model:

public function blogs()
    {
        return $this->hasMany('App\Blog');
    }

Blog Model:

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

In my BlogController, when I define the view, I grab a collection of blogs via $blogs = Blog::all();

In my view I just loop through the blogs to show each individually like...

@foreach ($blogs as $blog)
<div>{{ $blog->author->first_name }}</div>
@endforeach
Ad

Answer

For one to many relationship you don't need another table to handle your foreign key.

Just add author_id foreign key with your blogs table. then define your relations like below,

Author Model:

public function blogs()
{
   return $this->hasMany('App\Blog', 'author_id');
}

Blog Model:

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

view: before that make sure your query return a valid collection.

@foreach ($blogs as $blog)
<div>@if( $blog->author) {{ $blog->author->first_name }} @endif </div>
@endforeach

For further more details : https://laravel.com/docs/5.8/eloquent-relationships#one-to-many

Ad
source: stackoverflow.com
Ad