You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel资源控制器完整CRUD带筛选:语法及路由配置是否正确?

确认Laravel资源控制器与路由配置及筛选Index方法写法

一、路由配置(正确标准写法)

在routes/web.php中,对应你用php artisan make:model Item -mcr生成的资源控制器,路由需配置为:

use App\Http\Controllers\ItemController;

Route::resource('items', ItemController::class);

该配置会自动生成全套资源路由(index/create/store/show/edit/update/destroy),其中GET /items请求会直接映射到ItemController的index方法,符合资源控制器的设计逻辑。

二、带筛选功能的Index方法正确示例

以下是包含常见筛选逻辑的index方法实现,同时规避易犯的语法问题:

namespace App\Http\Controllers;

use App\Models\Item;
use Illuminate\Http\Request;

class ItemController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        // 初始化查询构造器
        $query = Item::query();

        // 按名称模糊筛选
        if ($request->filled('name')) {
            $query->where('name', 'like', '%' . $request->name . '%');
        }

        // 按状态精确筛选(用when方法简化条件判断)
        $query->when($request->input('status'), function ($q, $status) {
            $q->where('status', $status);
        });

        // 按创建时间范围筛选
        if ($request->filled('start_date')) {
            $query->whereDate('created_at', '>=', $request->start_date);
        }
        if ($request->filled('end_date')) {
            $query->whereDate('created_at', '<=', $request->end_date);
        }

        // 执行排序+分页
        $items = $query->orderBy('created_at', 'desc')->paginate(10);

        // 返回视图(API接口则返回json)
        return view('items.index', compact('items'));
    }
}

三、常见语法问题排查点

  • 链式调用遗漏:若直接写Item::where(...)却未赋值给变量,后续无法追加其他筛选条件,必须通过$query = Item::query()初始化后链式调用所有查询方法。
  • 模糊匹配语法错误:like查询时必须搭配百分号%,且避免直接拼接未校验的变量,用$request->filled()判断参数是否有效后再处理更安全。
  • when方法参数错误:闭包的第一个参数是查询构造器实例,第二个是传入的参数值,不要搞反顺序;若无需使用参数值,可改用$request->has()作为判断条件。
  • 分页时机错误:必须在所有筛选条件添加完成后调用paginate(),先分页再筛选会导致数据筛选不完整。

内容的提问来源于stack exchange,提问作者adyyyty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.02 01:17:28