我試圖執行搜索,以便用戶可以輸入書的標題,laravel將瀏覽數據庫並顯示匹配任何字符的結果。調用未定義的方法Illuminate Database Query Builder :: title()
我的'書籍'表包含'標題'字段。
但是如果我例如 'F' 我得到的輸入:
調用未定義的方法照亮\數據庫\查詢\生成器::標題()
搜索刀片:
@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
控制器:
function search()
{
$books = Book::all();
return view('layouts/search',['books' => $books]);
}
function details() {
$searchTerms = explode(' ', \Request::input('book'));
$books = Book::whereHas('title', function($query) use($searchTerms) {
if(!empty($searchTerms)){
for
each($searchTerms as $book) {
$query->where('book', 'LIKE', '%'. $book .'%');
}
}
})->first();
return view('layouts/details', compact('book'));
}
更新::
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.'%');
}
})->first();
return view('layouts/details', compact('books'));
}
你的縮進是一個爛攤子。你試圖在查詢時調用模型列(在用' - > get()'/ -'> first()'/' - > paginate()')結束查詢之前。 – devk
由於在視圖中需要集合,因此可以使用' - > get()'或' - > paginate()'。在返回視圖以檢查查詢實際返回的內容之前,還可以使用'dd($ books);'進行調試。 – Robert