1

In my laravel-application I have a blogs- and an author-table. On the index page, where you see all published blog posts, I want the authors name to appear. So I tried to do this:

public function index()
{

    $blogs = Blog::where("publishes_on", "<=", Carbon::now())
        ->orderBy('publishes_on', 'desc')
        ->published()
        ->get();

    foreach ($blogs as $blog) {
        $author = Author::where('id', $blog->author_id)->get();
    }

    return view('app.blog.index', compact('blogs', 'author'));
}

For some reason I do not know, this gives me the last added author to my application and on each post, the name of that author is displayed on all posts.

What am I doing wrong here?

1
  • You have to wire a Blog belongs to Author relationship and get the author`s details via that relationship Commented Sep 16, 2019 at 12:14

2 Answers 2

4

In Blog model add author relation

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

In controller

$blogs = Blog::where("publishes_on", "<=", Carbon::now())
    ->orderBy('publishes_on', 'desc')
    ->published()
    ->with('author:id,name')
    ->get();

In view you can use

@foreach($blogs  as $blog)
    // blog related data 
    Author: {{ $blog->author->name ?? '' }}
@endforeach
Sign up to request clarification or add additional context in comments.

2 Comments

Add the belongsTo relationship in the Blog model, just in case OP's missing that
This is awesome! Thanks a lot!! :-)
2

No need for the foreach loop

Blog::with('author')->where( [...]`

In your view

$blog->author->name

Make sure you define author() as a relationship on the Blog model:
https://laravel.com/docs/master/eloquent-relationships

e.g.

class Blog {
    function author(){
        return $this->belongsTo(Author::class);
    }
}

1 Comment

This is a nice answer too!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.