Access in the view the last values entered in the database

Asked

Viewed 170 times

1

I am trying to access the last "Books" inserted in the bank, and display in the view.

This controller function returns the view with the recovered values from the database.

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

The view is like this:

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

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

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

I cannot 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?

  • try passing the data to the view this way; return view('index', ['books' => $books]);

1 answer

1


At last one was missing get(); to return the data from this collection (Collections). The error is that it is being sent to view an object 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);
}
  • 1

    At the level of curiosity, what is the usefulness of a Builder object?

  • 1

    The object Builder would be the construction of their consultations, putting where, join, orderBy, limit, etc, but, it needs to have an order (or a finalizer) to bring results that can be get(), first() etc. ...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.