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

Laravel需求:仅允许用户查看自身提交的请求数据

Fix: Show Only Current User's Requests in Laravel

Hey there! I see the issue—your current query pulls all pending, unissued requests without filtering for the logged-in user. Let's adjust it to only show requests submitted by the current user, using your user_req junction table to link users and requests.

Modified Code

public function index() {
    // Get the ID of the currently authenticated user
    $currentUserId = Auth::id();

    $req = DB::table('particulars')
        ->join('reqs', 'particulars.particular_id', '=', 'reqs.particular_id')
        // Join the junction table to link requests with their associated users
        ->join('user_req', 'reqs.req_id', '=', 'user_req.req_id')
        ->select('particulars.*', 'reqs.*')
        ->where('status_req', '=', 'pending')
        ->where('status_issue', '=', 'not issued')
        // Filter to only include requests linked to the current user
        ->where('user_req.user_id', '=', $currentUserId)
        ->get();

    return view('requester.index', compact('req'));
}

Key Changes Explained

  • Auth::id(): This grabs the ID of the user currently logged into your app. Make sure your route is protected with the auth middleware (e.g., Route::get('/requests', [YourController::class, 'index'])->middleware('auth');) to ensure this value is never null.
  • Added user_req Join: Since you have a many-to-many relationship between users and reqs via the user_req table, we need to join this table to connect the logged-in user to their requests.
  • User Filter: The final where clause ensures we only retrieve requests where the user_id in user_req matches the current user's ID.

Quick Note

If your reqs table directly has a user_id column (instead of using a many-to-many junction), you can simplify the query by removing the user_req join and replacing the final where clause with:

->where('reqs.user_id', '=', $currentUserId)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:12:35