Easily add weighted searches through model attributes and relationships

Overview

Social Card of Laravel Searchable

Laravel Searchable 🔍

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

Easily add weighted searches through model attributes and relationships.

This package currently supports MySQL and PostgreSQL.

Installation

You can install the package via composer:

composer require h-farm/laravel-searchable

You can publish the config file with:

php artisan vendor:publish --provider="HFarm\Searchable\SearchableServiceProvider" --tag="searchable-config"

This is the content of the published config file:

return [
    /*
    |--------------------------------------------------------------------------
    | Default match weight
    |--------------------------------------------------------------------------
    |
    | The weight of all searched words which match at least one of the
    | list of searchable attributes.
    | Defaults to 1.
    |
    */

    'default_match_weight' => 1,
];

Usage

To use the package, add the HFarm\Searchable\HasSearch trait to each model you want to make searchable.

Once done, you can implement the getSearchableAttributes abstract method by returning the list of attributes (or relationships' attributes) you want to search for.

You can also define the weight of each searchable attribute. If no weight is specified then default_match_weight will be taken from config/searchable.php.

Here's an example model including the HasSearch trait:

<?php

namespace App\Models;

use HFarm\Searchable\HasSearch;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Facades\DB;

class Article extends Model
{
    use HasSearch;

    protected $fillable = [
        'id',
        'title',
        'body',
        'creator_name',
        'creator_surname',
    ];

    protected $casts = [
        'body' => 'array',
    ];

    /**
     * Get the model's searchable attributes.
     *
     * @return array
     */
    public function getSearchableAttributes(): array
    {
        return [
            'title' => 5, // Model attribute
            'body.en' => 2, // Single json key of a model attribute
            'tags.name', // Relationship attribute
            'tags.description.*', // All json keys of a relationship attribute
            DB::raw("CONCAT(creator_name, ' ', creator_surname)"), // Raw expressions are supported too
        ];
    }

    /**
     * Allows fetching the tags bound to current article instance
     *
     * @return BelongsToMany
     */
     public function tags(): BelongsToMany
     {
        return $this->belongsToMany(Tag::class)->withTimestamps();
     }
}

Now you can just search for a given term using the scopeSearch scope method:

use App\Models\Article;

$searchTerm = 'the search string';

Article::query()
    ->search($searchTerm)
    ->where('column', '=', 'something')
    ->get();

That's all!

The package generates an SQL query with an 'or' condition for each search term and each searchable fields. The given query returns all models matching the search terms. Furthermore, search results are weighted, which means the query will be ordered by the most matching models.

If you don't want to order the search results by its match weight, you can set the orderByWeight flag to false:

use App\Models\Article;

$searchTerm = 'the search string';

Article::query()
    ->search($searchTerm, false)
    ->where('column', '=', 'something')
    ->get();

Testing

composer test

Changelog

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

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

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

Comments
Releases(3.1.0)
Owner
H-FARM
H-FARM
Plastic is an Elasticsearch ODM and mapper for Laravel. It renders the developer experience more enjoyable while using Elasticsearch, by providing a fluent syntax for mapping, querying, and storing eloquent models.

Plastic is an Elasticsearch ODM and mapper for Laravel. It renders the developer experience more enjoyable while using Elasticsearch, by providing a f

Sleiman Sleiman 511 Dec 31, 2022
Sphinx Search library provides SphinxQL indexing and searching features

Sphinx Search Sphinx Search library provides SphinxQL indexing and searching features. Introduction Installation Configuration (simple) Usage Search I

Ripa Club 62 Mar 14, 2022
Store and retrieve objects from Algolia or Elasticsearch

Store and retrieve objects from a search index This is an opinionated Laravel 5.1 package to store and retrieve objects from a search index. Currently

Spatie 440 Dec 30, 2022
Unmaintained: Laravel Searchy makes user driven searching easy with fuzzy search, basic string matching and more to come!

!! UNMAINTAINED !! This package is no longer maintained Please see Issue #117 Here are some links to alternatives that you may be able to use (I do no

Tom Lingham 533 Nov 25, 2022
Build and execute an Elasticsearch search query using a fluent PHP API

PACKAGE IN DEVELOPMENT, DO NOT USE YET Build and execute ElasticSearch queries using a fluent PHP API This package is a lightweight query builder for

Spatie 94 Dec 14, 2022
symfony solarium integration and solr management

solarium-bundle symfony bundle for solarium integration and solr management. current state of this bundle for now this bundle is me messing about with

null 2 Jan 11, 2022
Fulltext indexing and searching for Laravel

Laravel fulltext index and search This package creates a MySQL fulltext index for models and enables you to search through those. Install Install with

SWIS 171 Jan 4, 2023
Search among multiple models with ElasticSearch and Laravel Scout

For PHP8 support use php8 branch For Laravel Framework < 6.0.0 use 3.x branch The package provides the perfect starting point to integrate ElasticSear

Sergey Shlyakhov 592 Dec 25, 2022
This package offers advanced functionality for searching and filtering data in Elasticsearch.

Scout Elasticsearch Driver ?? Introducing a new Elasticsearch ecosystem for Laravel. ?? This package offers advanced functionality for searching and f

Ivan Babenko 1.2k Dec 20, 2022
Vagrant configuration for PHP7, Phalcon 3.x and Zephir development.

Phalcon VM 2.0.1 Phalcon VM is an open source Vagrant configuration which contains wide range of tools required in modern web development. Like a Swis

Eugene Manuilov 42 Nov 17, 2022
This is an open source demo of smart search feature implemented with Laravel and Selectize plugin

Laravel smart search implementation See demo at: http://demos.maxoffsky.com/shop-search/ Tutorial at: http://maxoffsky.com/code-blog/laravel-shop-tuto

Maksim Surguy 215 Sep 8, 2022
This script was made to aid the process of migrating PHP and MySQL based websites

This script was made to aid the process of migrating PHP and MySQL based websites. Works with most common CMSes.

interconnect/it 3.9k Jan 5, 2023
A metadata catalog and search engine for geospatialized data

resto is a metadata catalog and a search engine dedicated to geospatialized data. Originally, it’s main purpose it to handle Earth Observation satellite imagery but it can be used to store any kind of metadata localized in time and space.

Jerome Gasperi 50 Nov 17, 2022
Laravel package to search through multiple Eloquent models. Supports sorting, pagination, scoped queries, eager load relationships and searching through single or multiple columns.

Laravel Cross Eloquent Search This Laravel package allows you to search through multiple Eloquent models. It supports sorting, pagination, scoped quer

Protone Media 844 Dec 25, 2022
cybercog 996 Dec 28, 2022
A trait to make building your own custom Laravel Model Searches a lot easier.

BrekiTomasson\LaravelModelFinder A simple trait that makes building your own custom Laravel Model Searches a lot easier and safer. It ensures that you

Breki Tomasson 3 Nov 27, 2022
Easily validate data attributes through a remote request

Laravel Remote Rule Easily validate data attributes through a remote request. This package allows you to define a subset of custom rules to validate a

H-FARM Innovation 27 Nov 20, 2022
Laravel-model-mapper - Map your model attributes to class properties with ease.

Laravel Model-Property Mapper This package provides functionality to map your model attributes to local class properties with the same names. The pack

Michael Rubel 15 Oct 29, 2022
Schedule your OLX searches and get notified by email when something new is published 📆

Olx.ba search scheduler Missing scheduler for Olx.ba searches. Production-ready small web application which notifies you by email when something new i

Benjamin Fajić 8 Nov 8, 2022
Searches for multilingual phrases in Laravel project and automatically generates language files for you.

Laravel Lang Generator Searches for multilingual phrases in a Laravel project and automatically generates language files for you. You can search for n

Gleb 5 Oct 19, 2022