php – 项目过滤laravel eloquent
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了php – 项目过滤laravel eloquent,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1526字,纯文字阅读大概需要3分钟。
内容图文
![php – 项目过滤laravel eloquent](/upload/InfoBanner/zyjiaocheng/734/f30b1fdbecc343fd953e4b981cbffcaa.jpg)
实现项目过滤功能的最佳方法是什么?
我有一个包含一些项目的表格,每个项目都有一些字段.
如何使用Laravel 5和Eloquent选择具有字段过滤功能的项目,如电子商务过滤?
解决方法:
我总是使用雄辩的范围来过滤雄辩的结果:https://laravel.com/docs/5.1/eloquent#query-scopes
你的控制器:
use App\Item;
class ItemController extends Controller
{
public function index(Request $request)
{
$items = Item::name($request->name)->price($request->price)->paginate(25);
return view('items.index', compact('items'));
}
}
你的型号:
class Item extends Model
{
public function scopeName($query, $name)
{
if (!is_null($name)) {
return $query->where('name', 'like', '%'.$name.'%');
}
return $query;
}
public function scopePrice($query, $price)
{
if (!is_null($price)) {
return $query->where(compact('price'));
}
return $query;
}
}
你的观点:
<form action="{{ route('items.index') }}" method="get">
<input type="text" name="price" />
<input type="text" name="name" />
<input type="submit" value="Search">
</form>
@foreach($items as $item)
{{ $item->name }}
@endforeach
{!! $items->render() !!}
在您的范围中,您可以在限制查询结果之前检查给定值是否为null.这有效地允许用户搜索和过滤分页结果.
您可以使用Laravel的Form Requests通过自动验证进一步增强搜索,这样您就可以确保他们搜索的输入与查询的数据类型相匹配.以下是使用上述示例的示例:
class ItemSearchRequest extends FormRequest
{
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'nullable|string|min:2|max:100',
'price' => 'nullable|numeric',
];
}
}
内容总结
以上是互联网集市为您收集整理的php – 项目过滤laravel eloquent全部内容,希望文章能够帮你解决php – 项目过滤laravel eloquent所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。