Skip to content

SDIjeremy/inertia-query-filter

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Inertia Query Filter

Latest Version on Packagist

Install

composer require bizhub/inertia-query-filter

Example

1. Create filter in App\QueryFilters

<?php

namespace App\QueryFilters;

use Bizhub\QueryFilter\QueryFilter;

class UserFilter extends QueryFilter
{
    public function trashed()
    {
        $this->builder->withTrashed();
    }
    
    public function status($value)
    {
        $this->builder->where('status', $value);
    }
}

2. Add Filterable trait to the model

<?php

namespace App\Models;

use Illuminate\Http\Request;
use Bizhub\QueryFilter\Filterable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Filterable;
}

3. Use filter scope

<?php

namespace App\Http\Controllers;

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

class UserController extends Controller
{
    /**
     * Get list of users
     *
     * @param Request $request
     * @return \Inertia\Response
     */
    public function index(Request $request)
    {
        return Inertia::render('Users/Index', [
            'users' => User::filter()->paginate()->withQueryString()
        ]);
    }
}

4. Use $inertia.replace in page/component

import throttle from 'lodash/throttle'
import pickBy from 'lodash/pickBy'
import mapValues from 'lodash/mapValues'

export default {
    props: ['users', 'filters'],

    data() {
        return {
            filter: {
                trashed: this.filters.trashed,
                status: this.filters.status
            }
        }
    },

    watch: {
        filter: {
            handler: throttle(function() {
                this.$inertia.replace(
                    route('users', pickBy(this.filter)), {
                        only: ['users'],
                    }
                )
            }, 500),
            deep: true
        }
    },

    methods: {
        clearFilter() {
            this.filter = mapValues(this.filter, () => null)
        }
    }
}

About

Laravel + Inertiajs query filters

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • PHP 100.0%