Laravel 5.4 如何实现搜索功能

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45815095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:32:11  来源:igfitidea点击:

How to implement search function in Laravel 5.4

phplaravellaravel-5.4

提问by Greg Ostry

I'm new to Laravel and have some understanding problems how can I implement a search function to my app.

我是 Laravel 的新手,有一些理解问题,如何为我的应用程序实现搜索功能。

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. '%');
    }
}

My controller looks like this:

我的控制器看起来像这样:

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'));
       }
    }

With php artisan tinker the model is working. I'm getting the db query.

使用 php artisan tinker,该模型正在运行。我正在获取数据库查询。

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>

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 serachTermfrom the controller

但是,现在,如果我在搜索输入字段中输入了一些内容,我如何从控制器中检索数据?该代码仅在我收到所有帖子时才有效。我需要以某种方式包含serachTerm来自控制器的

@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

回答by Brane

Firstly you need to install laravel scout

首先你需要安装 laravel scout

Use: composer require laravel/scout

用: composer require laravel/scout

Next you need to publish the Scout configuration using the vendor:publishcommand. This command will publish the scout.phpto your config directory.

接下来,您需要使用该vendor:publish命令发布 Scout 配置。此命令将发布scout.php到您的配置目录。

Here is the command: php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"

这是命令: php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"

Last step would be Laravel\Scout\Searchabletrait to the model you would like to make searchable.

最后一步是Laravel\Scout\Searchable您想要搜索的模型的特征。

Then its simple for use as: NameOfModel::search($searchText)->get();

然后它的使用很简单: NameOfModel::search($searchText)->get();

回答by wolacinio

Check this:

检查这个:

$posts = Post::search($searchTerm)->get();

回答by Henz Jason

You are trying to get all record and then applying your scope function, rather then get all records just try:

您正在尝试获取所有记录,然后应用范围函数,而不是尝试获取所有记录:

$searchTerm = $request->input('searchTerm');
$posts = Post::search($searchTerm);
return view('posts.index', compact('posts', 'searchTerm'));

回答by Adriano Michael

Laravel makes it really easy to do searches, as well as custom searches like live results, and etc. Just make sure to throttle your HTTP requests on the front end.

Laravel 使搜索和自定义搜索(如实时结果等)变得非常容易。只需确保在前端限制您的 HTTP 请求即可。

/**
 * Get a breed by name (returns similar results)
 * @param $term
 * @return \Illuminate\Http\JsonResponse
 */
public function getBreedByName($term)
{
    // Find an Breed by name
    $matchedTerm = Breed::where('text', 'LIKE', '%' . $term . '%')->get();
    return response()->json($matchedTerm);
}

Then create a reference to that controller and method in your routes. In my case, I used the following in /routes/api.php

然后在路由中创建对该控制器和方法的引用。就我而言,我在 /routes/api.php 中使用了以下内容

Route::get('/breeds/search/{term}', 'BreedsController@getBreedByName');

I hope this is helpful! Let me know if you have any questions or if this didn't cover your question.

我希望这是有帮助的!如果您有任何问题,或者这未涵盖您的问题,请告诉我。