作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个查找这些分页项目的产品类,但在前端我允许用户定义他希望每页显示多少项目(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/
我是一名优秀的程序员,十分优秀!