Irfan Iffi
Irfan Iffi

Reputation: 55

Query is not returning the data

I am trying to get searching data of Books by querying and by using filter. Below is my filter method.

$books = Book::join('authors', 'authors.id', '=', 'books.author_id')
                ->join('categories', 'categories.id', '=', 'books.category_id')
                ->join('publishers', 'publishers.id', '=', 'books.publisher_id');

        if (isset($book_name) && !empty($book_name)) {
            $books->where('books.name', 'like', '%' . $book_name . '%');
        }

        if (isset($author_id) && !empty($author_id)) {
            $books->where('authors.id', '=', $author_id);
        }

        if (isset($category_id) && !empty($category_id)) {
            $books->where('categories.id', '=', $category_id);
        }

        if (isset($publisher_id) && !empty($publisher_id)) {
            $books->where('publishers.id', '=', $publisher_id);
        }

        $books->get();

When I am trying to get the $books object, it returns me the Builder object.

Builder {#229 ▼
  #query: Builder {#240 ▶}
  #model: Book {#234 ▼
    +fillable: array:6 [▶]
    #connection: null
    #table: null
    #primaryKey: "id"
    #keyType: "int"
    #perPage: 15
    +incrementing: true
    +timestamps: true
    #attributes: []
    #original: []
    #relations: []
    #hidden: []
    #visible: []
    #appends: []
    #guarded: array:1 [▶]
    #dates: []
    #dateFormat: null
    #casts: []
    #touches: []
    #observables: []
    #with: []
    +exists: false
    +wasRecentlyCreated: false
    #reflection: null
  }
  #eagerLoad: []
  #macros: []
  #onDelete: null
  #passthru: array:11 [▶]
  #scopes: []
  #removedScopes: []
}

When I search books by the name of book that is present in database and apply foreach loop then it does not return me the required data. So What I do to get the $books object, so that, I could get perfect data?

Upvotes: 2

Views: 101

Answers (1)

Helioarch
Helioarch

Reputation: 1188

You have to assign the result of get() to your variable

...
$books = $books->get();

Upvotes: 2

Related Questions