Laravel Typeahead无法找到数据库项目

时间:2018-01-10 16:38:25

标签: php ajax twitter-bootstrap laravel-5 typeahead.js

我使用Laravel 5.4和Typeahead.js使用DB元素填充表单。正如我在这个平台上的新成员,我跟随this article来构建此表单。我已经按照搜索结果从我的数据库中找不到任何内容的所有内容。

这里有详细信息,

项目表

id | name | price
1  | Shoes| 4500
2  | Bags | 2500

项目模型

use Illuminate\Database\Eloquent\Model;
use Nicolaslopezj\Searchable\SearchableTrait;
use DB;
.................
........

use SearchableTrait;

protected $searchable = [
    'columns' => [
        'items.name' => 10,
        'items.id' => 8,
    ],
];

public $fillable = ['id', 'name', 'price'];

路由\ web.php

Route::get('test', 'SearchesController@index');
Route::get('finditems', 'SearchesController@finditems');

SearchesController.php

use App\Item;
.....................
..........
    public function index(){
        return view('test');
    }

    public function finditems(Request $request){
        return Item::search($request->get('q'))->get();
    }

视图\ test.blade.php

<form class="typeahead" role="search">
   {{ csrf_field() }}
   <input name="q" type="search" class="form-control search-input" placeholder="Search Items" autocomplete="off">
</form>
<script>
    jQuery(document).ready(function($) {
        // Options for "Bloodhound" suggestion engine
        var engine = new Bloodhound({
            remote: {
                url: '/finditems?q=%QUERY%',
                wildcard: '%QUERY%'
            },
            datumTokenizer: Bloodhound.tokenizers.whitespace('q'),
            queryTokenizer: Bloodhound.tokenizers.whitespace
        });

        $(".search-input").typeahead({
            hint: true,
            highlight: true,
            minLength: 1
        }, {
            source: engine.ttAdapter(),

            name: 'itemsList',

            templates: {
                empty: [
                    '<div class="list-group search-results-dropdown"><div class="list-group-item">Nothing found.</div></div>'
                ],
                header: [
                    '<div class="list-group search-results-dropdown">'
                ],
                suggestion: function (data) {
                    return '<a href="' + data.id + '" class="list-group-item">' + data.name + '- @' + data.price + '</a>'
                }
            }
        });
    });
</script>

注意:我在路由文件中使用了Route::get('finditems/{q}', 'SearchesController@finditems');。但结果一样!

编辑 - 它可以工作!

它的工作实际上!我忘了使用composer require "nicolaslopezj/searchable:1.*"

0 个答案:

没有答案