laravellaravel-blade

Laravel not able to display relationship name instead of id, even though defined as relation


I have defined relation between books and authors in my Laravel application like so:

my Book Model:

class Book extends Model
{
    use HasFactory;

    protected $table = 'books';

    protected $fillable = [
        'ISBN', 'publisher_id', 'author_id', 'year', 'title', 'price',
    ];

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

And here is my BookController index:

public function index()
{
    return view('books.index', [
        'books' => DB::table('books')->paginate(15)
    ]);
}

So now i want to display the author name instead of the author_id in my view:

@foreach ($books as $book)
    <tr>
        <td>{{ $book->author->name }}</td>
    </tr>
@endforeach

But i keep getting the error:

Undefined property: stdClass::$author (View: index.blade.php)

Solution

  • 'books' => DB::table('books')->paginate(15)
    

    when you use db, you are dealing with query builder, not eloquent query builder!

    you have to use the model itself and load the relation:

    'books' => Book::with(['author'])->paginate(15);