PHP code example of ahoysolutions / query-filters

1. Go to this page and download the library: Download ahoysolutions/query-filters 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/ */

    

ahoysolutions / query-filters example snippets


php artisan make:queryfilters PostFilters
www.example.com/posts?user=johnsmith&popular



namespace App\Filters;

use AhoySolutions\QueryFilters\QueryFilters;
use App\User;

class PostFilters extends QueryFilters
{
    /**
    * Filter the posts by the given user.
    *
    * @param string $username
    * @return \Illuminate\Database\Eloquent\Builder
    */
    protected function filterUser(string $username)
    {
        $user = User::where('username', $username)->firstOrFail();

        return $this->builder->where('artist_id', $user->id);
    }

    /**
     * Filter the posts by their popularity.
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    protected function filterPopular()
    {
        $this->resetOrderBy();

        return $this->builder->withCount('favorites')->orderBy('favorites_count', 'desc');
    }
}

// given url: /resource?popular

/**
 * Sorts the posts by their popularity.
 *
 * @return \Illuminate\Database\Eloquent\Builder
 */
protected function filterPopular()
{
    $this->resetOrderBy();

    return $this->builder->withCount('favorites')->orderBy('favorites_count', 'desc');
}