yogameleniawan / search-sort-eloquent
Searching & Sorting Column Eloquent Model
v1.2.1
2024-05-28 01:37 UTC
README
Install Package
composer require yogameleniawan/search-sort-eloquent
Add Dependency
Laravel 11
add provider to files bootstrap/providers.php
<?php return [ App\Providers\AppServiceProvider::class, ... Yogameleniawan\SearchSortEloquent\SearchSortServiceProvider::class, // add this line ];
Laravel 10, 9, 8 >
add provider to files config/app.php
'providers' => [ ... Yogameleniawan\SearchSortEloquent\SearchSortServiceProvider::class, // add this line ]
How to use
Searchable trait
Use Searchable trait to your model
use Yogameleniawan\SearchSortEloquent\Traits\Searchable; class User extends Model { use Searchable; .... }
Use search function to your eloquent model
class UserController extends Controller { public function search(Request $request) { $user = User::search( keyword: $request->keyword, columns: ["id", "name", "email"], )->get(); dd($user); } }
Query parameters:
localhost:8080/api/users?keyword=Yoga
Sortable trait
Use Sortable trait to your model
use Yogameleniawan\SearchSortEloquent\Traits\Sortable; class User extends Model { use Sortable; .... }
Use sort function to your eloquent model
class UserController extends Controller { public function sort(Request $request) { $user = User::sort( sort_by: $request->sort_by, sort_order: $request->sort_order )->get(); dd($user); } }
Query parameters:
localhost:8080/api/users?sort_by=name&sort_order=ASC
Combine Searchable & Sortable Trait
We can also combine these traits to eloquent model
class UserController extends Controller { public function sort(Request $request) { $user = User::search( keyword: $request->keyword, columns: ["id", "name", "email"], )->sort( sort_by: $request->sort_by, sort_order: $request->sort_order )->get(); dd($user); } }
Query parameters:
localhost:8080/api/users?keyword=Yoga&sort_by=name&sort_order=ASC
Changelog
Please see CHANGELOG for more information what has changed recently.
Credits
License
The MIT License (MIT). Please see License File for more information.