I am using model binding in a route and I want to handle the case where an id is missing from the database. According to the documentation you can use the missing method to handle this possibility. Is it possible to get the id that was passed to the route?
Using the following code I cannot find an attribute with the id when testing the route /document/idThatDoesNotExist
:
Route::middleware(['throttle:document'])
->resource('document', DocumentController::class)
->only(['show'])
->missing(function (Request $request) {
$request->dd();
});
As a temporary solution I have used the following piece of code to get the id but I wonder if there is a better way:
$document_id = preg_replace("/.*/document/(.*)/", "$1", $request->getRequestUri());
2
Answers
The missing method does not provide direct access to the ID that was passed to the route. To get the ID in the missing callback, you’ll need to extract it from the request’s URI or route parameters.
You can try:
Extracting the ID from the Request URI: You can use Laravel’s Route
facade to get the parameters of the current route, which can include
the ID you’re interested in.
Using Middleware to Extract the ID: If you want to handle this logic
in a centralized way, you can use middleware to extract the ID and handle the case where it’s missing.
you can pull route parameter values out of the
$request
object by using theroute('param_name', 'default_value')
method, in your case: