i am trying to Implement smart Search engine in my Laravel 5 With help of This Tutorial
https://maxoffsky.com/code-blog/laravel-shop-tutorial-3-implementing-smart-search/
i changes some code because this tutorial for laravel 4
now i am stuck here When i type any keywords like cup i got error on Network tab in my deleveloper tool
Call to undefined method Illuminate\Database\Query\Builder::products()
Here is my Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use App\Http\Requests;
use App\Product;
use App\Category;
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
));
}
}
my Product and Category model is blank because nothing on tutorial
Well based on your relationship between Product and Category Models you have to define product() function inside Category Model which represents your relationship. check This Link
For example - Assuming One-to-Many relationship (one category - Many Products) it will be like this -
Category Model -
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function product()
{
return $this->hasMany('App\Product');
// ^ this will change based on relationship
}
}
Product Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
public function category()
{
return $this->belongsTo('App\Category');
// ^ this will change based on relationship
}
}