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 theauthmiddleware (e.g.,Route::get('/requests', [YourController::class, 'index'])->middleware('auth');) to ensure this value is never null.- Added
user_reqJoin: Since you have a many-to-many relationship betweenusersandreqsvia theuser_reqtable, we need to join this table to connect the logged-in user to their requests. - User Filter: The final
whereclause ensures we only retrieve requests where theuser_idinuser_reqmatches 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
相关产品推荐
相关产品推荐

