98.全文搜索(五)
- 本系列文章为
laracasts.com
的系列视频教程——Let's Build A Forum with Laravel and TDD 的学习笔记。若喜欢该系列视频,可去该网站订阅后下载该系列视频, 支持正版 ;- 视频源码地址:github.com/laracasts/Lets-Build-a-...;
- 本项目为一个 forum(论坛)项目,与本站的第二本实战教程 《Laravel 教程 - Web 开发实战进阶》 类似,可互相参照。
本节说明
- 对应视频教程第 98 小节:First Class Search: Forum Integration
本节内容
上一节我们在 scan 页面实验了实时响应的高级搜索功能,本节我们应用到系统中。首先我们需要修改SearchController
控制器的show()
方法:
forum\app\Http\Controllers\SearchController.php
<?php
namespace App\Http\Controllers;
use App\Thread;
use App\Trending;
class SearchController extends Controller
{
public function show(Trending $trending)
{
if (request()->expectsJson()) {
return Thread::search(request('q'))->paginate(20);
}
return view('threads.search',[
'trending' => $trending->get()
]);
}
}
现在我们搜索话题的结果会显示在新的页面上,并且在该页面上可以进行实时响应的高级搜索:
forum\resources\views\threads\search.blade.php
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row">
<ais-index
app-id="{{ config('scout.algolia.id') }}"
api-key="{{ config('scout.algolia.key') }}"
index-name="threads"
query="{{ request('q') }}"
>
<div class="col-md-8">
<ais-results>
<template scope="{ result }">
<li>
<a :href="result.path">
<ais-highlight :result="result" attribute-name="title"></ais-highlight>
</a>
</li>
</template>
</ais-results>
</div>
<div class="col-md-4">
<div class="panel panel-default">
<div class="panel-heading">
Search
</div>
<div class="panel-body">
<ais-search-box>
<ais-input placeholder="Find a thread..." :autofocus="true" class="form-control"></ais-input>
</ais-search-box>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
Filter By Channel
</div>
<div class="panel-body">
<ais-refinement-list attribute-name="channel.name"></ais-refinement-list>
</div>
</div>
@if(count($trending))
<div class="panel panel-default">
<div class="panel-heading">
Trending Threads
</div>
<div class="panel-body">
<ul class="list-group">
@foreach($trending as $thread)
<li class="list-group-item">
<a href="{{ url($thread->path) }}">
{{ $thread->title }}
</a>
</li>
@endforeach
</ul>
</div>
</div>
@endcan
</div>
</ais-index>
</div>
</div>
@endsection
注:
<ais-></ais->
标签均可在 components 找到对应的说明文档,请仔细查看。
顺便添加样式:
forum\resources\views\layouts\app.blade.php
<style>
body{ padding-bottom: 100px; }
.level { display: flex;align-items: center; }
.level-item { margin-right: 1em; }
.flex { flex: 1 }
.mr-1 {margin-right: 1em;}
.ml-a { margin-left: auto; }
[v-cloak] { display: none; }
.ais-highlight > em { background: yellow;font-style: normal; }
</style>
进行测试:
最后,我们运行全部测试: