wstam/eloquentfilter

此包实现了将简单的模型过滤功能集成到Laravel模型中,并在模板中生成HTML过滤器

0.1 2017-09-30 18:13 UTC

This package is not auto-updated.

Last update: 2024-09-29 05:01:28 UTC


README

EloquentFilter为Laravel Eloquent模型添加了新的功能,使数据过滤变得简单。

安装EloquentFilter

您需要使用Composer将EloquentFilter安装到项目中

composer require wstam/eloquentfilter

配置(Laravel)

现在您需要在config/app.php中包含EloquentFilterServiceProvider

'providers' => [
    /*
     * Package Service Providers...
     */
    WStam\EloquentFilter\EloquentFilterServiceProvider::class,
]

现在我们需要运行以下Artisan命令在终端中发布默认的blade视图

php artisan vendor:publish --provider="WStam\EloquentFilter\EloquentFilterServiceProvider"

现在您在vendor/eloquentfilter视图文件夹中有container.blade.phpfilter.blade.php。您可以根据自己的需求更改过滤器容器的模板以及过滤器本身。

如何使用EloquentFilter

例如,您想为Product模型添加过滤功能。将过滤特性添加到模型中,如下所示

<?php

namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
use WStam\EloquentFilter\EloquentFilterable;
 
class Product extends Model
{
    use EloquentFilterable;
}

现在您可以为Query Builder对象指定过滤器

/**
 * Show all the products
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $products = Product::query()->orderBy('title', 'ASC');
 
    // addFilter($column, $label = null, $type = 'text', $default = null, $comparison = '=')
 
    $products->addFilter('title', 'Title', 'text');
    $products->addFilter('external_supplier', 'External supplier', 'boolean');
    
    // Use filterCollection instead of get() to implement the "renderFilter" method into the collection
    $productCollection = $products->filterCollection();
 
    return view('product.index', ['products' => $productCollection]);
}

现在您可以在blade模板中渲染过滤器

<!-- This renders the filters. You can change the filter views at vendor/eloquentfilter -->
{!! $products->renderFilters() !!}
 
<div class="table-responsive">
    <table class="table table-bordered table-striped">
        <thead>
            <tr>
                <th>Title</th>
                <th>External supplier</th>
            </tr>
        </thead>
        <tbody>
        @foreach($products as $product)
            <tr>
                <td>
                    <a href="{{ route('product_edit', $product->id) }}">{{$product->title}}</a>
                </td>
                <td>
                    @if($product->external_supplier == 1)
                        Yes
                    @else
                        No
                    @endif
                </td>
            </tr>
        @endforeach
        </tbody>
    </table>
</div>

贡献

对于扩展/增强这个库有好的想法吗?请随时贡献并发送pull request!

许可证

EloquentFilter是开源软件,遵循MIT许可证