Tuesday, April 11, 2017

Laravel search not returning any result

I am trying to create a search where user can search for book title. There is a field in 'books' table called 'title'.

however if I do dd($books); I get:

Collection {#667 ▼
  #items: []
}

If I do dd($searchTerms); output seems to be correct

Here's my controller:

    function search()
    {
        $books = Book::all();
        return view('layouts/search',['books' => $books]);
    }
        function details() {
            $searchTerms = explode(' ', \Request::input('book')); 
            $books = Book::where(function($q) use($searchTerms) {
            foreach ($searchTerms as $book) {
             $q->orWhere('title', '%'.$book.'%');
            }
        })->get();
            dd($books);
        return view('layouts/details', compact('books'));
}

Search blade:

@extends('layouts.master')

@section('title')

@section('content')
    <h1>Search for books</h1>
    <form action="" method="POST">
    
        <div>
            <input type='text'  name='book' placeholder='Enter any character' />
        </div>
    <input type="submit" name="submitBtn" value="Search">
    </form>
@endsection

Details blade:

@extends('layouts.master')

@section('title')

@section('content')
    <h1>User Details</h1>
      <form>
      <p>
    <ul>
      @foreach ($books as $book)
    <a href=  "">
      </a>
      </p>
</form>
@endforeach
    </ul>
@endsection



via Przemek

Advertisement