PHP code example of ahmedwaleed / laravel-query-filter

1. Go to this page and download the library: Download ahmedwaleed/laravel-query-filter library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ahmedwaleed / laravel-query-filter example snippets


// app/Queries/ScopeActiveUsersQuery.php

namespace App\Queries;

use AhmedWaleed\QueryFilter\QueryScope;

class ScopeActiveUsersQuery extends QueryScope
{
    /**
     * Add query to applicable model
     *
     * @param \Illuminate\Database\Eloquent\Builder $builder
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function apply($builder)
    {
        //

        return $builder;
    }
}



namespace App;

use Illuminate\Database\Eloquent\Model;
use AhmedWaleed\QueryFilter\QueryScopes;

class User extends Model
{
  use QueryScopes;
  
  //
}

//..
public function index()
{
  $users = User::addQuery(
    (new ScopeActiveUsersQuery())->when(request()->has('active'))
  )->get();
  
  return view('users.index', compact('users'));
}
//..


$users = User::addQuery(
    (new ScopeActiveUsersQuery())->when(request()->has('active'))
)->addQuery(
    (new ScopeUsersLocationQuery())->when(request()->has('location'))
)->get();


$users = User::addQuery(new ScopeActiveUsersQuery())->get();

// controller
$data = ['limit' => 10, 'status' => request('active')];

$users = User::addQuery(new ScopeActiveUsersQuery($data))->get();

// App\Queries\ScopeActiveUsersQuery.php

namespace App\Queries;

use AhmedWaleed\QueryFilter\QueryScope;

class ScopeActiveUsersQuery extends QueryScope
{
    /**
     * Add query to applicable model
     *
     * @param \Illuminate\Database\Eloquent\Builder $builder
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function apply($builder)
    {
        $builder->whereStatus($this->data['status'] ?? 1)
          ->limit($this->data['limit'] ?? 50);

        return $builder;
    }
}
bash
php artisan make:query ScopeActiveUsersQuery