我正在尝试实现智能搜索引擎这是教程链接
https://github.com/msurguy/laravel-smart-search
我知道 Laravel 4 的这个教程,我想在 Laravel 5.2 中实现
现在我卡住了
我无法获取 api/search 的 json 格式
这是我的路线
Route::get('api/search', 'ApiSearchController@index');
这是我在 App/http/controller 中使用 Artisan 的帮助程序创建的控制器,我确实尝试创建类似教程 api/searchcontroller 的内容,但它无法正常工作,总是出现错误“ApiSearchController@index 未找到”
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use App\Http\Requests;
use App\Product;
use Response;
class ApiSearchController extends Controller
{
public function appendValue($data, $type, $element)
{
// operate on the item passed by reference, adding the element and type
foreach ($data as $key => & $item) {
$item[$element] = $type;
}
return $data;
}
public function appendURL($data, $prefix)
{
// operate on the item passed by reference, adding the url based on slug
foreach ($data as $key => & $item) {
$item['url'] = url($prefix.'/'.$item['slug']);
}
return $data;
}
public function index()
{
$query = e(Input::get('q',''));
if(!$query && $query == '') return Response::json(array(), 400);
$products = Product::where('published', true)
->where('name','like','%'.$query.'%')
->orderBy('name','asc')
->take(5)
->get(array('slug','name','icon'))->toArray();
$categories = Category::where('name','like','%'.$query.'%')
->has('products')
->take(5)
->get(array('slug', 'name'))
->toArray();
// Data normalization
$categories = $this->appendValue($categories, url('img/icons/category-icon.png'),'icon');
$products = $this->appendURL($products, 'products');
$categories = $this->appendURL($categories, 'categories');
// Add type of data to each item of each set of results
$products = $this->appendValue($products, 'product', 'class');
$categories = $this->appendValue($categories, 'category', 'class');
// Merge all data into one array
$data = array_merge($products, $categories);
return Response::json(array(
'data'=>$data
));
}
}
当我打开 http://localhost/search/public/api/search
我应该像教程一样从数据库中获取所有数据
但无法得到
其他事情是一样的
请告诉我出了什么问题
您的搜索不起作用,因为它期望提供一个查询来作为查询字符串或请求的一部分进行搜索。
Input::get('q')
表示从您的查询字符串或请求中检索 q
并将其用于搜索。
当您进入
http://localhost/search/public/api/search
页面时,您是按照GET
请求进行操作的,因此需要像这样提供您的查询http://localhost/search/public/api/search?q=example
。
本教程中的示例使用 AJAX 运行
GET
请求,该请求会为您执行上述操作。
尝试在 URL 末尾添加
?q=xxxx
,如果您按照该教程进行了适当的设置,它应该可以工作。