All Projects → spatie → Laravel Searchable

spatie / Laravel Searchable

Licence: mit
Pragmatically search through models and other sources

Projects that are alternatives of or similar to Laravel Searchable

Searchable
Search/filter functionality for Laravel's Eloquent models
Stars: ✭ 113 (-83.88%)
Mutual labels:  search, laravel
Lara Eye
Filter your Query\Builder using a structured query language
Stars: ✭ 39 (-94.44%)
Mutual labels:  search, laravel
Laravel Cross Eloquent Search
Laravel package to search through multiple Eloquent models. Supports sorting, pagination, scoped queries, eager load relationships and searching through single or multiple columns.
Stars: ✭ 189 (-73.04%)
Mutual labels:  search, laravel
Laravel Lucene Search
Laravel 4.2, 5.* package for full-text search over Eloquent models based on ZF2 Lucene.
Stars: ✭ 75 (-89.3%)
Mutual labels:  search, laravel
Laravel Api Handler
Package providing helper functions for a Laravel REST-API
Stars: ✭ 150 (-78.6%)
Mutual labels:  search, laravel
Searchable
A php trait to search laravel models
Stars: ✭ 1,923 (+174.32%)
Mutual labels:  search, laravel
Scout Extended
Scout Extended: The Full Power of Algolia in Laravel
Stars: ✭ 330 (-52.92%)
Mutual labels:  search, laravel
Laravel Responder
A Laravel Fractal package for building API responses, giving you the power of Fractal with Laravel's elegancy.
Stars: ✭ 673 (-3.99%)
Mutual labels:  laravel
Laravel Terminal
Runs artisan command in web application
Stars: ✭ 682 (-2.71%)
Mutual labels:  laravel
Laravel Json Api
JSON API (jsonapi.org) package for Laravel applications.
Stars: ✭ 667 (-4.85%)
Mutual labels:  laravel
Laravel Web Tinker
Tinker in your browser
Stars: ✭ 664 (-5.28%)
Mutual labels:  laravel
Hifone
A free, open-source, self-hosted forum software based on the Laravel PHP Framework. QQ群:656868
Stars: ✭ 673 (-3.99%)
Mutual labels:  laravel
Laravel Media Manager
A "Vuejs & Laravel" Media Manager With Tons of Features
Stars: ✭ 684 (-2.43%)
Mutual labels:  laravel
Sleepingowladmin
🦉 Administrative interface builder for Laravel (Laravel admin)
Stars: ✭ 671 (-4.28%)
Mutual labels:  laravel
Antvel
[DEPRECATED] > Use "https://github.com/ant-vel/App" instead!!!
Stars: ✭ 696 (-0.71%)
Mutual labels:  laravel
Laravel Repositories
[ABANDONED] Rinvex Repository is a simple, intuitive, and smart implementation of Active Repository with extremely flexible & granular caching system for Laravel, used to abstract the data layer, making applications more flexible to maintain.
Stars: ✭ 664 (-5.28%)
Mutual labels:  laravel
Sweet Alert
A BEAUTIFUL, RESPONSIVE, CUSTOMIZABLE, ACCESSIBLE (WAI-ARIA) REPLACEMENT FOR JAVASCRIPT'S POPUP BOXES FOR LARAVEL
Stars: ✭ 696 (-0.71%)
Mutual labels:  laravel
Laravel Ubuntu Init
A shell script for setting up Laravel Production environment on Ubuntu 14.04 & Ubuntu 16 & Ubuntu 18 system.
Stars: ✭ 695 (-0.86%)
Mutual labels:  laravel
Invoiceninja
Invoices, Expenses and Tasks built with Laravel and Flutter
Stars: ✭ 6,247 (+791.16%)
Mutual labels:  laravel
Dsa.js Data Structures Algorithms Javascript
🥞Data Structures and Algorithms explained and implemented in JavaScript + eBook
Stars: ✭ 6,251 (+791.73%)
Mutual labels:  search

Laravel Searchable

Latest Version on Packagist Test Status Code Style Status Total Downloads

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 [email protected] instead of using the issue tracker.

Credits

License

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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].