gpt4 book ai didi

laravel - 如何在 Laravel 中动态设置每页的最大值?

转载 作者:行者123 更新时间:2023-12-04 00:25:48 25 4
gpt4 key购买 nike

我有一个查找这些分页项目的产品类,但在前端我允许用户定义他希望每页显示多少项目(10、30、50、100)问题是如果有人通过 1000,API 每页返回 1000 条记录。

我如何为所有 Controller 和模型动态验证这一点?

我可以通过验证每个 Controller 上的每个请求(“限制”)来“轻松”地做到这一点,但这不切实际,我该怎么做?

public function index(Request $request)
{
$perPage = $request->input('limit'); // User input
$sort = 'global_performance';
$descending = 'desc';
$products = Product::where('status', 1)
->orderBy($sort, $descending)
->paginate($perPage); //

return $products;
}

最佳答案

您可以像这样验证限制:

public function index(Request $request)
{
$this->validate($request, [
'limit' => ['required', 'integer', Rule::in([10, 30, 50, 100])]
]);
$perPage = $request->input('limit'); // User input
$sort = 'global_performance';
$descending = 'desc';
$products = Product::where('status', 1)
->orderBy($sort, $descending)
->paginate($perPage); //

return $products;
}

现在,在 Controller 类之前添加以下行:

use Illuminate\Validation\Rule;

更新

更动态的方式可能是像这样创建自定义请求类:

运行以下命令创建一个新的表单请求类:

php artisan make:request PaginateRequest

这将在 App\Http\Requests 目录中创建 PaginateRequest 类,如下所示:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class PaginateRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return false;
}

/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
//
];
}
}

现在将此类更改为以下内容:

<?php

namespace App\Http\Requests;

use Illuminate\Validation\Rule;
use Illuminate\Foundation\Http\FormRequest;

class PaginateRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}

/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'limit' => ['required', 'integer', Rule::in([10, 30, 50, 100])]
];
}
}

在此之后,您可以通过将其添加为函数参数来在 Controller 函数中使用。

public function index(PaginateRequest $request)
{
$perPage = $request->input('limit'); // User input
$sort = 'global_performance';
$descending = 'desc';
$products = Product::where('status', 1)
->orderBy($sort, $descending)
->paginate($perPage); //

return $products;
}

请不要忘记像这样在 Controller 类之前导入它:

use App\Http\Requests\PaginateRequest;

这样,你就可以在任何你需要的地方使用这个请求类。

您可以在此处的文档中查看更多信息:https://laravel.com/docs/5.8/validation

关于laravel - 如何在 Laravel 中动态设置每页的最大值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57056325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com