Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Laravel package to search through multiple Eloquent models. Supports sorting, pagination, scoped queries, eager load relationships and searching through single or multiple columns.

License

NotificationsYou must be signed in to change notification settings

protonemedia/laravel-cross-eloquent-search

Repository files navigation

Latest Version on Packagistrun-testsTotal DownloadsBuy us a tree

This Laravel package allows you to search through multiple Eloquent models. It supports sorting, pagination, scoped queries, eager load relationships, and searching through single or multiple columns.

Sponsor Us

❤️ We proudly support the community by developing Laravel packages and giving them away for free. If this package saves you time or if you're relying on it professionally, please considersponsoring the maintenance and development and check out our latest premium package:Inertia Table. Keeping track of issues and pull requests takes time, but we're happy to help!

Requirements

  • PHP 8.2 or higher
  • MySQL 8.0+
  • Laravel 10.0+

Features

📺 Want to watch an implementation of this package? Rewatch the live stream (skip to 13:44 for the good stuff):https://youtu.be/WigAaQsPgSA

Blog post

If you want to know more about this package's background, please readthe blog post.

Installation

You can install the package via composer:

composer require protonemedia/laravel-cross-eloquent-search

Upgrading from v2 to v3

  • Theget method has been renamed tosearch.
  • TheaddWhen method has been removed in favor ofwhen.
  • By default, the results are sorted by theupdated column, which is theupdated_at column in most cases. If you don't use timestamps, it will now use the primary key by default.

Upgrading from v1 to v2

  • ThestartWithWildcard method has been renamed tobeginWithWildcard.
  • The default order column is now evaluated by thegetUpdatedAtColumn method. Previously it was hard-coded toupdated_at. You still can useanother column to order by.
  • TheallowEmptySearchQuery method andEmptySearchQueryException class have been removed, but you can stillget results without searching.

Usage

Start your search query by adding one or more models to search through. Call theadd method with the model's class name and the column you want to search through. Then call thesearch method with the search term, and you'll get a\Illuminate\Database\Eloquent\Collection instance with the results.

The results are sorted in ascending order by theupdated column by default. In most cases, this column isupdated_at. If you'vecustomized your model'sUPDATED_AT constant, or overwritten thegetUpdatedAtColumn method, this package will use the customized column. If you don't use timestamps at all, it will use the primary key by default. Of course, you canorder by another column as well.

useProtoneMedia\LaravelCrossEloquentSearch\Search;$results = Search::add(Post::class,'title')    ->add(Video::class,'title')    ->search('howto');

If you care about indentation, you can optionally use thenew method on the facade:

Search::new()    ->add(Post::class,'title')    ->add(Video::class,'title')    ->search('howto');

There's also anwhen method to apply certain clauses based on another condition:

Search::new()    ->when($user->isVerified(),fn($search) =>$search->add(Post::class,'title'))    ->when($user->isAdmin(),fn($search) =>$search->add(Video::class,'title'))    ->search('howto');

Wildcards

By default, we split up the search term, and each keyword will get a wildcard symbol to do partial matching. Practically this means the search termapple ios will result inapple% andios%. If you want a wildcard symbol to begin with as well, you can call thebeginWithWildcard method. This will result in%apple% and%ios%.

Search::add(Post::class,'title')    ->add(Video::class,'title')    ->beginWithWildcard()    ->search('os');

Note: in previous versions of this package, this method was calledstartWithWildcard().

If you want to disable the behaviour where a wildcard is appended to the terms, you should call theendWithWildcard method withfalse:

Search::add(Post::class,'title')    ->add(Video::class,'title')    ->beginWithWildcard()    ->endWithWildcard(false)    ->search('os');

Multi-word search

Multi-word search is supported out of the box. Simply wrap your phrase into double-quotes.

Search::add(Post::class,'title')    ->add(Video::class,'title')    ->search('"macos big sur"');

You can disable the parsing of the search term by calling thedontParseTerm method, which gives you the same results as using double-quotes.

Search::add(Post::class,'title')    ->add(Video::class,'title')    ->dontParseTerm()    ->search('macos big sur');

Sorting

If you want to sort the results by another column, you can pass that column to theadd method as a third parameter. Call theorderByDesc method to sort the results in descending order.

Search::add(Post::class,'title','published_at')    ->add(Video::class,'title','released_at')    ->orderByDesc()    ->search('learn');

You can call theorderByRelevance method to sort the results by the number of occurrences of the search terms. Imagine these two sentences:

  • Apple introduces iPhone 13 and iPhone 13 mini
  • Apple unveils new iPad mini with breakthrough performance in stunning new design

If you search forApple iPad, the second sentence will come up first, as there are more matches of the search terms.

Search::add(Post::class,'title')    ->beginWithWildcard()    ->orderByRelevance()    ->search('Apple iPad');

Ordering by relevance isnot supported if you're searching through (nested) relationships.

To sort the results by model type, you can use theorderByModel method by giving it your preferred order of the models:

Search::new()    ->add(Comment::class, ['body'])    ->add(Post::class, ['title'])    ->add(Video::class, ['title','description'])    ->orderByModel([        Post::class, Video::class, Comment::class,    ])    ->search('Artisan School');

Pagination

We highly recommend paginating your results. Call thepaginate method before thesearch method, and you'll get an instance of\Illuminate\Contracts\Pagination\LengthAwarePaginator as a result. Thepaginate method takes three (optional) parameters to customize the paginator. These arguments arethe same as Laravel's database paginator.

Search::add(Post::class,'title')    ->add(Video::class,'title')    ->paginate()// or    ->paginate($perPage =15,$pageName ='page',$page =1)    ->search('build');

You may also usesimple pagination. This will return an instance of\Illuminate\Contracts\Pagination\Paginator, which is not length aware:

Search::add(Post::class,'title')    ->add(Video::class,'title')    ->simplePaginate()// or    ->simplePaginate($perPage =15,$pageName ='page',$page =1)    ->search('build');

Constraints and scoped queries

Instead of the class name, you can also pass an instance of theEloquent query builder to theadd method. This allows you to add constraints to each model.

Search::add(Post::published(),'title')    ->add(Video::where('views','>',2500),'title')    ->search('compile');

Multiple columns per model

You can search through multiple columns by passing an array of columns as the second argument.

Search::add(Post::class, ['title','body'])    ->add(Video::class, ['title','subtitle'])    ->search('eloquent');

Search through (nested) relationships

You can search through (nested) relationships by using thedot notation:

Search::add(Post::class, ['comments.body'])    ->add(Video::class, ['posts.user.biography'])    ->search('solution');

Full-Text Search

You may useMySQL's Full-Text Search by using theaddFullText method. You can search through a single or multiple columns (usingfull text indexes), and you can specify a set of options, for example, to specify the mode. You can even mix regular and full-text searches in one query:

Search::new()    ->add(Post::class,'title')    ->addFullText(Video::class,'title', ['mode' =>'boolean'])    ->addFullText(Blog::class, ['title','subtitle','body'], ['mode' =>'boolean'])    ->search('framework -css');

If you want to search through relationships, you need to pass in an array where the array key contains the relation, while the value is an array of columns:

Search::new()    ->addFullText(Page::class, ['posts' => ['title','body'],'sections' => ['title','subtitle','body'],    ])    ->search('framework -css');

Sounds like

MySQL has asoundex algorithm built-in so you can search for terms that sound almost the same. You can use this feature by calling thesoundsLike method:

Search::new()    ->add(Post::class,'framework')    ->add(Video::class,'framework')    ->soundsLike()    ->search('larafel');

Eager load relationships

Not much to explain here, but this is supported as well :)

Search::add(Post::with('comments'),'title')    ->add(Video::with('likes'),'title')    ->search('guitar');

Getting results without searching

You call thesearch method without a term or with an empty term. In this case, you can discard the second argument of theadd method. With theorderBy method, you can set the column to sort by (previously the third argument):

Search::add(Post::class)    ->orderBy('published_at')    ->add(Video::class)    ->orderBy('released_at')    ->search();

Counting records

You can count the number of results with thecount method:

Search::add(Post::published(),'title')    ->add(Video::where('views','>',2500),'title')    ->count('compile');

Model Identifier

You can use theincludeModelType to add the model type to the search result.

Search::add(Post::class,'title')    ->add(Video::class,'title')    ->includeModelType()    ->paginate()    ->search('foo');// Example result with model identifier.{"current_page":1,"data": [        {"id":1,"video_id":null,"title":"foo","published_at":null,"created_at":"2021-12-03T09:39:10.000000Z","updated_at":"2021-12-03T09:39:10.000000Z","type":"Post",        },        {"id":1,"title":"foo","subtitle":null,"published_at":null,"created_at":"2021-12-03T09:39:10.000000Z","updated_at":"2021-12-03T09:39:10.000000Z","type":"Video",        },    ],    ...}

By default, it uses thetype key, but you can customize this by passing the key to the method.

You can also customize thetype value by adding a public methodsearchType() to your model to override the default class base name.

class Videoextends Model{publicfunctionsearchType()    {return'awesome_video';    }}// Example result with searchType() method.{"current_page":1,"data": [        {"id":1,"video_id":null,"title":"foo","published_at":null,"created_at":"2021-12-03T09:39:10.000000Z","updated_at":"2021-12-03T09:39:10.000000Z","type":"awesome_video",        }    ],    ...

Standalone parser

You can use the parser with theparseTerms method:

$terms = Search::parseTerms('drums guitar');

You can also pass in a callback as a second argument to loop through each term:

Search::parseTerms('drums guitar',function($term,$key) {//});

Testing

composertest

Changelog

Please seeCHANGELOG for more information about what has changed recently.

Contributing

Please seeCONTRIBUTING for details.

Other Laravel packages

  • Inertia Table: The Ultimate Table for Inertia.js with built-in Query Builder.
  • Laravel Blade On Demand: Laravel package to compile Blade templates in memory.
  • Laravel Eloquent Scope as Select: Stop duplicating your Eloquent query scopes and constraints in PHP. This package lets you re-use your query scopes and constraints by adding them as a subquery.
  • Laravel FFMpeg: This package provides an integration with FFmpeg for Laravel. The storage of the files is handled by Laravel's Filesystem.
  • Laravel MinIO Testing Tools: Run your tests against a MinIO S3 server.
  • Laravel Mixins: A collection of Laravel goodies.
  • Laravel Paddle: Paddle.com API integration for Laravel with support for webhooks/events.
  • Laravel Task Runner: Write Shell scripts like Blade Components and run them locally or on a remote server.
  • Laravel Verify New Email: This package adds support for verifying new email addresses: when a user updates its email address, it won't replace the old one until the new one is verified.
  • Laravel XSS Protection: Laravel Middleware to protect your app against Cross-site scripting (XSS). It sanitizes request input, and it can sanatize Blade echo statements.

Security

If you discover any security-related issues, please emailpascal@protone.media instead of using the issue tracker.

Credits

License

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

Treeware

This package isTreeware. If you use it in production, we ask that youbuy the world a tree to thank us for our work. By contributing to the Treeware forest, you'll create employment for local families and restoring wildlife habitats.

About

Laravel package to search through multiple Eloquent models. Supports sorting, pagination, scoped queries, eager load relationships and searching through single or multiple columns.

Topics

Resources

License

Stars

Watchers

Forks

Sponsor this project

 

Contributors8

Languages


[8]ページ先頭

©2009-2025 Movatter.jp