PHP code example of mehdi-fathi / eloquent-filter

1. Go to this page and download the library: Download mehdi-fathi/eloquent-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/ */

    

mehdi-fathi / eloquent-filter example snippets




namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index(Request $request)
    {
        $users = User::where('is_active', true);

        if ($request->has('age_more_than')) {
            $users->where('age', '>', $request->age_more_than);
        }

        if ($request->has('gender')) {
            $users->where('gender', $request->gender);
        }

        if ($request->has('created_at')) {
            $users->where('created_at','>=', $request->created_at);
        }

        return json_encode($users->get());
    }
}

/**
 * Class UsersController.
 */

namespace App\Http\Controllers;

use App\User;

class UsersController
{
    public function list()
    {
        return User::filter()->get();
    }
}

   'providers' => [
     /*
      * Package Service Providers...
      */
       eloquentFilter\ServiceProvider::class
   ]
   

'alias' => [
  /*
   * Facade alias...
   */
    'EloquentFilter' => eloquentFilter\Facade\EloquentFilter::class,
],

use eloquentFilter\QueryFilter\ModelFilters\Filterable;

class User extends Model
{
    use Filterable;
    
    private static $whiteListFilter =[
        'id',
        'username',
        'email',
        'created_at',
        'updated_at',
    ];
}

private static $whiteListFilter = ['*'];

User::setWhiteListFilter(['name']); 

User::addWhiteListFilter('name'); 

use eloquentFilter\QueryFilter\ModelFilters\Filterable;

class User extends Model
{
    use Filterable;
   
    private static $whiteListFilter =[
        'username',
        'posts.count_post',
        'posts.category',
        'posts.orders.name',
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\belongsTo
     */
    public function posts()
    {
        return $this->belongsTo('Models\Post');
    }

}

$builder = (new User())->with('posts');
        $builder->whereHas('posts', function ($q) {
            $q->where('count_post', 876);
        })->where('username','mehdi');


namespace App\ModelFilters;

use Illuminate\Database\Eloquent\Builder;

/**
 * Trait UsersFilter.
 */
trait UsersFilter
{
    /**
     * This is a sample custom query
     * @param \Illuminate\Database\Eloquent\Builder $builder
     * @param                                       $value
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function filterCustomSample_like(Builder $builder, $value)
    {
        return $builder->where('username', 'like', '%'.$value.'%');
    }
}


use App\ModelFilters\UsersFilter;

class User extends Model
{
    use UsersFilter,Filterable;

    protected $table = 'users';
    protected $guarded = [];
    private static $whiteListFilter =[
        'id',
        'username',
        'email',
        'created_at',
        'updated_at',
    ];
    
}

User::filter()->paginate();


use eloquentFilter\QueryFilter\Detection\Contract\ConditionsContract;

/**``
 * Class WhereRelationLikeCondition.
 */
class WhereRelationLikeCondition implements ConditionsContract
{
    /**
     * @param $field
     * @param $params
     * @param $is_override_method
     *
     * @return string|null
     */
    public static function detect($field, $params, $is_override_method = false): ?string
    {
        if (!empty($params['value']) && !empty($params['limit']) && !empty($params['email'])) {
            $method = WhereRelationLikeConditionQuery::class;
        }

        return $method ?? null;
    }
}

use eloquentFilter\QueryFilter\Queries\BaseClause;
use Illuminate\Database\Eloquent\Builder;

/**
 * Class WhereRelationLikeConditionQuery.
 */
class WhereRelationLikeConditionQuery extends BaseClause
{
    /**
     * @param $query
     *
     * @return Builder
     */
    public function apply($query): Builder
    {
        return $query
            ->whereHas('posts', function ($q) {
                $q->where('comment', 'like', "%" . $this->values['like_relation_value'] . "%");
            })
            ->where("$this->filter", '<>', $this->values['value'])
            ->where('email', 'like', "%" . $this->values['email'] . "%")
            ->limit($this->values['limit']);
    }
}

use eloquentFilter\QueryFilter\ModelFilters\Filterable;

class User extends Model
{
    use Filterable;
   
    private static $whiteListFilter =[
        'username',
        'posts.count_post',
        'posts.category',
        'posts.orders.name',
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\belongsTo
     */
    public function posts()
    {
        return $this->belongsTo('Models\Post');
    }

    public function EloquentFilterCustomDetection(): array
    {
        return [
            WhereRelationLikeCondition::class
        ];
    }

}

$users = User::SetCustomDetection([WhereRelationLikeCondition::class])->filter();

 User::SetLoadDefaultDetection(false)->filter();


class User extends Model
{
    use Filterable;
    public function EloquentFilterCustomDetection(): array
    {
        return [
            WhereRelationLikeCondition::class,
            WhereRelationLikeVersion2Condition::class,
            WhereRelationLikeVersion3Condition::class,
        ];
    }
}


    class Stat extends Model
    {
        use Filterable;
        /**
         * @var array
         */
        private static $whiteListFilter = [
            'type',
            'national_code',
        ];

        /**
         * @var array
         */
        private $aliasListFilter = [
            'national_code' => 'code',
        ];
    }


 DB::table('users')->filter();

          
  $users = User::ignoreRequest(['name'])
            ->filter()
            ->with('posts')
            ->orderByDesc('id')
            ->paginate(request()->get('perpage'),['*'],'page');


  $user = new User();
  $users = $user->ignoreRequestFilter(['name','family'])
            ->filter()
            ->with('posts')
            ->orderByDesc('id')
            ->paginate(request()->get('perpage'),['*'],'page');



User::ignoreRequest(['perpage'])
            ->filter()
            ->paginate(request()->get('perpage'), ['*'], 'page');

``
User::AcceptRequest(['username','id'])
            ->filter()
            ->paginate(request()->get('perpage'), ['*'], 'page');


$user = new User();
$user->acceptRequestFilter(['username','id'])
            ->filter()
            ->paginate(request()->get('perpage'), ['*'], 'page');


class User extends Model
{
    use Filterable;
    
    private static $whiteListFilter =[
        'username'
    ];
    
    public function serializeRequestFilter($request)
    {
       $request['username'] = trim($request['username']);
       return $request;
    }
}


class Category extends Model
{
    use Filterable;
    
    private static $whiteListFilter =[
        'desc'
    ];
    
    public function filterSetDesc($value)
    {
        return trim($value);
    }
}


class User extends Model
{
    use Filterable;
    public function getResponseFilter($response)
    {
        $data['data'] = $response;
        return $data;
    }
}


$categories = DB::table('categories')->filter()->getResponseFilter(function ($out) {

    $data['data'] = $out;

    return $data;
});



namespace App\Http\Controllers;

/**
 * Class UsersController.
 */
class UsersController
{

    public function list()
    {
              $users = User::setBlackListDetection(
                  [
                      'WhereCondition',
                  ]
                )->filter()
                ->orderByDesc('id')
                ->paginate();
    }
}



namespace Tests\Models;

use eloquentFilter\QueryFilter\ModelFilters\Filterable;
use Illuminate\Database\Eloquent\Model;

class Car extends Model
{
    use Filterable;
    
    private static $whiteListFilter = '*';

    protected $black_list_detections = [
        'WhereCondition',
    ];
}

    $users = User::SetCustomDetection([WhereRelationLikeCondition::class])->filter();
    echo $users->isUsedEloquentFilter(); // will true
    echo $users->getDetectionsInjected(); // will showing a list array of injected objects
    $categories = DB::table('categories')->filter();
    echo $categories->isUsedEloquentFilter(); // will true
    

/users/list?username[]=ali&username[]=ali22&family=ahmadi

SELECT ... WHERE ... username in ('ali','ali22') AND family = 'ahmadi'

/users/list?count_posts[operator]=>&count_posts[value]=35

SELECT ... WHERE ... count_posts > 35

/users/list?posts[category][]=php&posts[category][]=laravel&posts[category][]=jquery&username=mehdi

select * from "users" where exists 
         (select * from "posts" where 
         "posts"."category" in ('php','laravel','jquery') )
         and "username" = "mehdi"