我正在使用 laravel 7,我正在嘗試在我的專案中實作搜索。這是我的控制器搜索功能代碼
public function search(Request $request)
{
$search = Request::get('search');
$posts = Post::table('posts')
->where('title', 'like', '%' . $search . '%')
->paginate(5);
return view('dashboard', ['posts' => $posts]);
}
這是路線
Route::get('/search', 'PostsController@search');
這是我的搜索條碼
<form action="/search" method="get">
<div class="input-group">
<input type="search" name="search" class="form-control">
<span class="input-group-prepend">
<button type="submit" class="btn btn-primary">Search</button>
</span>
</div>
</form>
這是儀表板刀片中的表格
@if(count($posts) > 0)
<table class="table table-bordered">
<tr>
<thead class="table-dark">
<th>Entry#</th>
<th>Consignee</th>
<th>Description</th>
<th>Uploaded By</th>
<th>Date Uploaded</th>
<th>Actions</th>
<th>Status</th>
</thead>
</tr>
@foreach ($posts as $post)
<tbody id="myTable" name="myTable">
<tr>
<td>{{$post->title}}</td>
<td>{{$post->consignee}}</a></td>
<td>{!!$post->body!!}</td>
<td>{{$post->user->name}}</td>
<td>{{$post->created_at}}</td>
<td>
<a href="/posts/{{$post->id}}/" class="btn btn-primary">View</a>
<button type="button" class="btn btn-danger" data-toggle="modal" href="#deletePost{{$post->id}}">
Delete
</button>
</td>
<td>{{$post->status}}</td>
</tr>
@endforeach
</tbody>
</table>
{{$posts->links()}}
@else
<p> You have no entries</p>
@endif
我的表格看起來像這樣
我希望當我按下搜索按鈕時它看起來像這樣 我
不知道為什么搜索沒有在資料表上顯示任何內容似乎是什么問題。請告訴我如何解決這個問題。謝謝
uj5u.com熱心網友回復:
不需要table('posts')在 eloquent 模型類中定義,因為模型總是將表名設定為它的類名(復數形式)。還有一件事,當未設定搜索查詢引數時,無需應用 where 條件。如果在搜索變數中分配了任何值,則應使用 where 條件。
請這樣做。
public function search (Request $request)
{
$search = $request->get('search');
$posts = Post::when($search, function($sql) use ($search) {
$sql->where('title', 'like', '%' . $search . '%');
})
->paginate(5);
return view('dashboard', compact('posts'));
}
uj5u.com熱心網友回復:
您在 Blade 迭代中的主要問題。請將 count($posts) 替換為 $posts->total() 方法。因為 $posts 是分頁資料物件而不是陣列串列。
@if($posts->total() > 0)
<table class="table table-bordered">
<tr>
<thead class="table-dark">
<th>Entry#</th>
<th>Consignee</th>
<th>Description</th>
<th>Uploaded By</th>
<th>Date Uploaded</th>
<th>Actions</th>
<th>Status</th>
</thead>
</tr>
<tbody id="myTable" name="myTable">
@foreach ($posts as $post)
<tr>
<td>{{$post->title}}</td>
<td>{{$post->consignee}}</a></td>
<td>{!!$post->body!!}</td>
<td>{{$post->user->name}}</td>
<td>{{$post->created_at}}</td>
<td>
<a href="/posts/{{$post->id}}/" class="btn btn-primary">View</a>
<button type="button" class="btn btn-danger" data-toggle="modal" href="#deletePost{{$post->id}}">
Delete
</button>
</td>
<td>{{$post->status}}</td>
</tr>
@endforeach
</tbody>
</table>
{{$posts->links()}}
@else
<p> You have no entries</p>
@endif
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/365241.html
上一篇:自定義計劃事件不會觸發
下一篇:php對WEBP影像元資料的支持
