当前位置: 首页 > 软件库 > Web应用开发 > Web框架 >

laravel-searchable

授权协议 MIT License
开发语言 PHP
所属分类 Web应用开发、 Web框架
软件类型 开源软件
地区 不详
投 递 者 吕骞尧
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

Laravel Searchable

This package makes it easy to get structured search from a variety of sources. Here's an example where we search through some models. We already did some small preparation on the models themselves.

$searchResults = (new Search())
   ->registerModel(User::class, 'name')
   ->registerModel(BlogPost::class, 'title')
   ->search('john');

The search will be performed case insensitive. $searchResults now contains all User models that contain john in the name attribute and BlogPosts that contain 'john' in the title attribute.

In your view you can now loop over the search results:

<h1>Search</h1>

There are {{ $searchResults->count() }} results.

@foreach($searchResults->groupByType() as $type => $modelSearchResults)
   <h2>{{ $type }}</h2>
   
   @foreach($modelSearchResults as $searchResult)
       <ul>
            <li><a href="{{ $searchResult->url }}">{{ $searchResult->title }}</a></li>
       </ul>
   @endforeach
@endforeach

In this example we used models, but you can easily add a search aspect for an external API, list of files or an array of values.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via composer:

composer require spatie/laravel-searchable

Usage

Preparing your models

In order to search through models you'll have to let them implement the Searchable interface.

namespace Spatie\Searchable;

interface Searchable
{
    public function getSearchResult(): SearchResult;
}

You'll only need to add a getSearchResult method to each searchable model that must return an instance of SearchResult. Here's how it could look like for a blog post model.

use Spatie\Searchable\Searchable;
use Spatie\Searchable\SearchResult;

class BlogPost extends Model implements Searchable
{
     public function getSearchResult(): SearchResult
     {
        $url = route('blogPost.show', $this->slug);
     
         return new \Spatie\Searchable\SearchResult(
            $this,
            $this->title,
            $url
         );
     }
}

Searching models

With the models prepared you can search them like this:

$searchResults = (new Search())
   ->registerModel(User::class, 'name')
   ->search('john');

The search will be performed case insensitive. $searchResults now contains all User models that contain john in the name attribute.

You can also pass multiple attributes to search through:

// use multiple model attributes

$searchResults = (new Search())
   ->registerModel(User::class, 'first_name', 'last_name')
   ->search('john');
   
// or use an array of model attributes

$searchResults = (new Search())
   ->registerModel(User::class, ['first_name', 'last_name'])
   ->search('john');

To get fine grained control you can also use a callable. This way you can also search for exact matches, apply scopes, eager load relationships, or even filter your query like you would using the query builder.

$search = (new Search())
   ->registerModel(User::class, function(ModelSearchAspect $modelSearchAspect) {
       $modelSearchAspect
          ->addSearchableAttribute('name') // return results for partial matches on usernames
          ->addExactSearchableAttribute('email') // only return results that exactly match the e-mail address
          ->active()
          ->has('posts')
          ->with('roles');
});

Creating custom search aspects

You are not limited to only registering basic models as search aspects. You can easily create your own, custom search aspects by extending the SearchAspect class.

Consider the following custom search aspect to search an external API:

class OrderSearchAspect extends SearchAspect
{
    public function getResults(string $term): Collection
    {
        return OrderApi::searchOrders($term);
    }
}

This is how you can use it:

$searchResults = (new Search())
   ->registerAspect(OrderSearchAspect::class)
   ->search('john');

Limiting aspect results

It is possible to limit the amount of results returned by each aspect by calling limitAspectResults prior to performing the search.

$searchResults = (new Search())
    ->registerAspect(BlogPostAspect::class)
    ->limitAspectResults(50)
    ->search('How To');

Rendering search results

Here's an example on rendering search results:

<h1>Search</h1>

There are {{ $searchResults->count() }} results.

@foreach($searchResults->groupByType() as $type => $modelSearchResults)
   <h2>{{ $type }}</h2>
   
   @foreach($modelSearchResults as $searchResult)
       <ul>
            <a href="{{ $searchResult->url }}">{{ $searchResult->title }}</a>
       </ul>
   @endforeach
@endforeach

You can customize the $type by adding a public property $searchableType on your model or custom search aspect

class BlogPost extends Model implements Searchable
{
    public $searchableType = 'custom named aspect';
}

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email freek@spatie.be instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

  • Laravel-RediSearch允许索引和搜索Laravel模型。它提供了Laravel Scout驱动程序。 安装 composer require ethanhann/laravel-redisearch 注册提供商 将此条目添加到config / app.php中的providers数组中。 Ehann\LaravelRediSearch\RediSearchServiceProvid

 相关资料
  • Laravel 是一套简洁、优雅的PHP Web开发框架(PHP Web Framework)。它可以让你从面条一样杂乱的代码中解脱出来;它可以帮你构建一个完美的网络APP,而且每行代码都可以简洁、富于表达力。 功能特点 1、语法更富有表现力 你知道下面这行代码里 “true” 代表什么意思么? $uri = Uri::create(‘some/uri’, array(), array(), tr

  • 我需要空间/Laravel权限的帮助。当我试图分配它给我错误哎呀,看起来像出了问题。 错误 Connection.php第761行中的QueryExcema:SQLSTATE[23000]:完整性约束冲突:1048列role_id不能为空(SQL:插入到(,)值(9,))

  • Laravel 作为现在最流行的 PHP 框架,其中的知识较多,所以单独拿出来写一篇。 简述 Laravel 的生命周期 Laravel 采用了单一入口模式,应用的所有请求入口都是 public/index.php 文件。 注册类文件自动加载器 : Laravel通过 composer 进行依赖管理,无需开发者手动导入各种类文件,而由自动加载器自行导入。 创建服务容器:从 bootstrap/ap

  • 简介 Laravel Scout 为 Eloquent 模型 全文搜索提供了简单的,基于驱动的解决方案。通过使用模型观察者,Scout 会自动同步 Eloquent 记录的搜索索引。 目前,Scout 自带一个 Algolia 驱动;不过,编写自定义驱动很简单, 你可以轻松的通过自己的搜索实现来扩展 Scout。 安装 首先,通过 Composer 包管理器来安装 Scout: composer

  • 简介 Laravel 致力于让整个 PHP 开发体验变得愉快, 包括你的本地开发环境。 Vagrant 提供了一种简单,优雅的方式来管理和配置虚拟机。 Laravel Homestead 是一个官方预封装的 Vagrant box,它为你提供了一个完美的开发环境,而无需在本地机器安装 PHP 、Web 服务器和其他服务器软件。不用担心会搞乱你的操作系统!Vagrant boxes 是一次性的。如果

  • WebStack-Laravel 一个开源的网址导航网站项目,具备完整的前后台,您可以拿来制作自己的网址导航。 部署 克隆代码: git clone https://github.com/hui-ho/WebStack-Laravel.git 安装依赖: composer installphp artisan key:generate 编辑配置: cp .env.example .env ...D