macsidigital / laravel-searchable
Search eloquent models and filter matching results for a url get request
Requires
- php: ^7.2
- illuminate/support: ^6.0|^7.0
Requires (Dev)
- orchestra/testbench: ^4.0
- phpunit/phpunit: ^8.0
README
A package to make searching eloquent models from a single search field easier
Installation
You can install the package via composer:
composer require macsidigital/laravel-searchable
The service provider should automatically register for For Laravel > 5.4.
For Laravel < 5.5, open config/app.php and, within the providers array, append:
MacsiDigital\Searchable\Providers\SearchableServiceProvider::class
Usage
Create 2 arrays in your elequent model, the first with the fields that can be sorted, the second showing any table joins.
protected $searchable = [ 'name', 'email', ]; protected $extended_joins = [ 'addresses.country' => [ 'table_field' => 'users.id', 'foreign_table_field' => 'addresses.addressable_id', 'restrict_table_field' => 'addresses.addressable_type', 'restrict_value' => 'App\User' ] ];
If no table joins are required then you will only need the searchable array.
For any joins include the table and field seperated by a period (.).
Then to search the fields simply add a form and input named 'search' into your page that uses a get request. Use the @searchableformurl to create the form request
<form class="inline-form" action="@searchableformurl()" method="GET"> <div class="input-group"> <input type="text" class="form-control" placeholder="Search" aria-label="Search" aria-describedby="search" name="search"> <div class="input-group-append"> <button class="btn btn-outline-secondary" type="submit" id="search"><i class="fas fa-search"></i></button> </div> </div> </form>
Changelog
Please see CHANGELOG for more information what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security
If you discover any security related issues, please email colin@macsi.co.uk instead of using the issue tracker.
Credits
License
The MIT License (MIT). Please see License File for more information.