Access in the view the last values entered in the database

1

I'm trying to access the latest "books" inserted in the database, and display in the view.

This function of the controller returns the view with the values retrieved from the bank.

public function index(){
        $books = Book::orderBy('created_at', 'desc')->take(5);
        return view('index')->with('books', $books);
    }

In the view it looks like this:

@foreach($books as $book)
        {{$book->name}}
@endforeach

But nothing is displayed (there is data in the database), using {{dd($books)}} I have this as a return:

Builder {#180 ▼
  #query: Builder {#179 ▶}
  #model: Book {#168 ▶}
  #eagerLoad: []
  #macros: []
  #onDelete: null
  #passthru: array:11 [▶]
  #scopes: []
  #removedScopes: []
}

I can not understand why the foreach is not displaying the values, since dd () shows that the object was passed. How can I correctly access the values of the last 5 books?

    
asked by anonymous 11.10.2016 / 23:13

1 answer

1

Finally a get(); was missing to return the data from this collection ( Collections ). The error is that you are sending an object to view Builder ( object(Illuminate\Database\Eloquent\Builder) ).

Code

public function index()
{
    $books = Book::orderBy('created_at', 'desc')->take(5)->get();
    return view('index')->with('books', $books);
}
    
12.10.2016 / 00:31