我正在尝试创建一个用户可以搜索图书标题的搜索。 “书籍”表中有一个名为“title”的字段。
然而,如果我做dd($ books);我明白了:Collection {#667 ▼
#items: []
}
如果我做dd($ searchTerms);输出似乎是正确的
这是我的控制器:
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'));
}
搜索刀片:
@extends('layouts.master')
@section('title')
@section('content')
<h1>Search for books</h1>
<form action="{{url('details')}}" method="POST">
{{ csrf_field() }}
<div>
<input type='text' name='book' placeholder='Enter any character' />
</div>
<input type="submit" name="submitBtn" value="Search">
</form>
@endsection
详情刀片:
@extends('layouts.master')
@section('title')
@section('content')
<h1>User Details</h1>
<form>
<p>
<ul>
@foreach ($books as $book)
<a href= "{{url('reader/'.$book->title)}}">
{{$book->title}}</a>
</p>
</form>
@endforeach
</ul>
@endsection
答案 0 :(得分:1)
您忘记告诉雄辩的构建者您的OR
应该LIKE
作为运营商:
$q->orWhere('title', 'like', '%'.$book.'%');
答案 1 :(得分:0)
请将详细信息的功能更改为
function details(Request $request) {
$searchTerms = $request->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'));
}