leandreaci/filterable

该包的最新版本(1.2.3)没有可用的许可信息。

筛选 Laravel/Lumen 包

安装: 428

依赖: 1

建议者: 0

安全: 0

星星: 2

关注者: 2

分支: 0

开放问题: 0

类型:

1.2.3 2022-04-28 19:30 UTC

This package is auto-updated.

Last update: 2024-09-29 00:57:23 UTC


README

根据查询字符串筛选模型

示例:domain.com/route?id=1

安装包

composer require leandreaci/filterable *@dev

使用

在您的 Laravel/Lumen 项目中创建一个文件

  • app/Filters/ExampleFilter.php
<?php


namespace App;


use Carbon\Carbon;
use Leandreaci\Filterable\QueryFilter;

class ExampleFilter extends QueryFilter
{

    public function id($id)
    {
        return $this->builder->where('id', $id);
    }

    public function start($date)
    {
        try{
            $formattedDate = Carbon::createFromFormat('Y-m-d', $date)->startOfDay()->toDateTimeString();
            return $this->builder->where('created_at','>', $formattedDate);
        }catch (\Exception $exception)
        {
            return $this->builder;
        }
    }
    

}
  • 使用 Filterable Trait 到您想筛选的模型
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Leandreaci\Filterable\Filterable;

class ExampleModel extends Model
{
    use Filterable;
}

?>
  • 在控制器中
<?php

namespace App\Http\Controllers;

use App\ExampleModel;

class TransactionController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @param ExampleFilter $filter
     * @return TransactionsCollection
     */
    public function index(ExampleFilter $filter)
    {
        return  ExampleModel::filter($filter)
                               ->paginate(10);
    }
}
?>