musa11971/laravel-sort-request

待定

此包的官方仓库似乎已消失,因此该包已被冻结。

1.0.1 2020-02-14 13:00 UTC

This package is auto-updated.

Last update: 2022-12-15 05:13:53 UTC


README

logo.png

Latest version on packagist GitHub Tests Action Status Quality score Total downloads

因为你有更重要的事情要做

请求的排序逻辑,但更加简化

此Laravel包使得将排序逻辑集成到您的应用中变得更加容易。
考虑以下示例

# Get the cheapest items
https://example.test/items?sort=price(asc)

# Get the items sorted by name and size
https://example.test/items?sort=name(asc),size(desc)

# Get the most popular TV Shows (custom sorting behavior)
https://example.test/tv-shows?sort=popularity(most-popular)

安装

您可以通过composer安装此包

composer require musa11971/laravel-sort-request

使用方法

基本排序

SortsViaRequest特质添加到您的Laravel表单请求中。

class GetItemsRequest extends FormRequest
{
    use SortsViaRequest;

    /**
     * Get the rules that the request enforces.
     *
     * @return array
     */
    function rules()
    {
        return array_merge([
            // This is where your normal validation rules go
        ], $this->sortingRules());
    }

    /**
     * Returns the columns that can be sorted on.
     *
     * @return array
     */
    function getSortableColumns(): array
    {
        return [
            'id', 'stackSize', 'displayName'
        ];
    }
}

如上所示,您还需要在表单请求中实现getSortableColumns方法。它应该返回一个可以排序的列名数组。
所以如果您只想允许在“名称”和“价格”列上进行排序,您将这样做

function getSortableColumns(): array
{
    return ['name', 'price'];
}

接下来,前往您的控制器并按以下方式添加sortViaRequest方法

class ItemController extends Controller
{
    /**
     * Returns a list of all items as JSON.
     *
     * @param GetItemsRequest $request
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    function get(GetItemsRequest $request)
    {
        $items = Item::sortViaRequest($request)->get();

        // Do something with your models...
    }
}

😎 就这么简单。您现在可以使用“sort”参数对模型进行排序。

# Sort a single column
https://example.test/items?sort=price(asc)

# Sort multiple columns
https://example.test/items?sort=price(asc),name(desc),experience(asc)

自定义排序

此包还允许您实现自定义排序行为,例如以下示例

# Get the worst ranking users
https://example.test/user?sort=ranking(worst)

# Get the most delicious pastries, and sort them by cheapest
https://example.test/pastries?sort=taste(most-delicious),price(cheapest)

有关如何使用此功能的指南,请参阅自定义排序文档

测试

composer test

贡献

有关详细信息,请参阅CONTRIBUTING

安全性

如果您发现任何与安全性相关的问题,请通过电子邮件mussesemou99@gmail.com联系,而不是使用问题跟踪器。

致谢

感谢musa11971创建和维护此包。

特别感谢

支持我

我是一名全职软件工程学生,并在业余时间开发此包。如果您认为此包很有用,请考虑进行捐款!每一分钱都很有帮助。 💜

许可

麻省理工学院许可证(MIT)。有关更多信息,请参阅许可文件