Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading