如何在Laravel 5.4中实现搜索功能
我是Laravel的新手,对如何实现应用程序的搜索功能有一些理解上的问题.
I'm new to Laravel and have some understanding problems how can I implement a search function to my app.
到目前为止我尝试过的.
What I have tried so far.
我创建了一个从数据库获取数据的模型(正在运行)
I created a model that gets the data from the db (this is working)
class Post extends Model
{
public static function scopeSearch($query, $searchTerm)
{
return $query->where('city', 'like', '%' .$searchTerm. '%')
->orWhere('name', 'like', '%' .$searchTerm. '%');
}
}
我的控制器如下:
use App\Post;
class PostsController extends Controller
{
public function index(Request $request)
{
$searchTerm = $request->input('searchTerm');
$posts = Post::all()
->search($searchTerm);
return view('posts.index', compact('posts', 'searchTerm'));
}
public function show($id)
{
$post = Post::find($id);
return view('posts.show', compact('post'));
}
}
使用php artisan tinker,模型正在运行.我正在获取数据库查询.
With php artisan tinker the model is working. I'm getting the db query.
在前端,我有一个带有提交按钮的简单输入字段:
On the front-end I have a simple input field with a submit button:
<div class="container">
<div class="col-sm-8">
<form action="posts.index" method="GET">
{{csrf_field()}}
<div class="input-group">
<input type="text" class="form-control" name="searchTerm" placeholder="Search for..." value="{{ isset($searchTerm) ? $searchTerm : '' }}">
<span class="input-group-btn">
<button class="btn btn-secondary" type="submit">Search</button>
</span>
</div>
</form>
</div>
</div>
但是,现在,如果我在搜索输入字段中输入内容,如何从控制器中检索数据?该代码仅在我收到所有帖子时才有效.我需要以某种方式包括控制器中的 serachTerm
But, now, how can I retrieve the data from the controller if I input something in the search input field? The code is only working when I get all the posts. I need to include somehow the serachTerm
from the controller
@extends('layouts.master')
@section('content')
<div class="col-sm-8 blog-main">
@foreach($posts as $post)
<div class="card" style="margin-bottom: 10px">
<div class="card-block">
<h3 class="card-title">{{ $post->Name1 }}</h3>
<small>Created at: {{ $post->created_at->toFormattedDateString() }}</small>
<p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
<a href="{{$post->id}}" class="btn btn-primary">Details</a>
</div>
</div>
@endforeach
</div>
@endsection
检查此内容:
$posts = Post::search($searchTerm)->get();