Advanced Eloquent Search Query Filters

While using the Laravel framework, which is a framework used to build websites, you might come across advanced eloquent search query filters which is used to search from the specific data provided. These advanced eloquent search query filters are most commonly used when you have multiple filter options.

Advanced Eloquent Search Query Filters

To perform this complex search easily you may use Laravel Eloquent builder which will speed up your process of making the query much simpler and more effective both speed-wise and readability-wise. This Laravel Eloquent BUilder can be downloaded from here.

 

Once you download and install the package, you can use the following code which demonstrates the use of filters on 

the user.

Laravel Search



<?php
namespace App\EloquentFilters\User;
use Fouladgar\EloquentBuilder\Support\Foundation\Contracts\Filter;
use Illuminate\Database\Eloquent\Builder;
class AgeMoreThanFilter implements Filter
{

    /**
     * Apply the age condition to the query.
     *
     * @param Builder $builder
     * @param mixed   $value
     *
     * @return Builder
     */

    public function apply(Builder $builder, $value): Buialder
    {
        return $builder->where('age', '>', $value);
    }
}


The above mentioned code can be used to add any new filter to your search query.

<?php
namespace App\Http\Controllers;
use App\User;
use EloquentBuilder;
use Illuminate\Http\Request;
class UserController extends Controller
{
    public function index(Request $request)
    {
        $users = EloquentBuilder::to(
                    User::class,
                    $request->all()
                 );
        return $users->get();
    }
}

WIth this code, you can implement advanced eloquent search query filters and can be add multiple filters to the search query. The complete guide can be viewed here.

 

Building faceted search can always be very tricky and having a good solution to that can save a slot of trouble. Solr faceted search is something you can consider in such a case wherein you are looking to make a faceted search engine. 

Add Google custom  Search to your website

Learn about Query Building using the Laravel Eloquent Builder

You may also like