Back

Binding user ID in Laravel requests without the headache: Extend FormRequest, override prepareForValidation(), and merge the user()->id automatically. This way, no need to pass user_id in every request manually! πŸŽ‰


image
image

2 β€’ β€’

130

β€’
  • No matching results...
  • Searching...

/ 1000

In what cases would you prefer that over calling `auth()->user()` in the Controller?

1 β€’ β€’

150

β€’

My approach ensures cleaner controllers and allows for logic reuse across various parts of my API project at least from my perspective :D. It's perfect for consistently binding and validating the user ID.

For simpler cases where it's only needed in one place, I directly use auth()->user() within the controller.

β€’ β€’

167

β€’

You could also do this for all requests with middleware:

class WithUserId
{
public function handle(Request $request, Closure $next): Response
{
$request->merge([
'user_id' => $request->input('user_id') ?: $request->user()?->id,
]);

return $next($request);
}
}


This wouldn't override the user id if it was actually set in the request, but would inject `user_id` into the input for each request that passes through it.

β€’ β€’

270

β€’