I have a method in my controller where I return an array of books from a database like so:
$books= DB::table('books')->where('category_id', $category_id)->orderBy('title', 'asc')->paginate(20);
Now I want to be able to use an eloquent relationship with the resulting array of books like this in my view:
@foreach($books as $book)
<p>Title: {!! $book->title !!}
<p>Category: {!! $book->category() !!}
@endforeach
From my understanding this will not work because the $books array is not in Eloquent. How can I make it so it does this?
I assume you already have Book
and category
model and both have relationship to each other
Try this:
$books= Book::with('category')->orderBy('title', 'asc')->paginate(20);