So, I have a controller in Laravel that handles URLs.
public function showEvents($course)
{
// function for the /events/{$course} pages
try {
[$view, $id] = match ($course) {
// URL Request from ($course) then the set the $view and $id
'lorem' => ['pages.course.lorem', '2'],
'impsum' => ['pages.course.impsum', '3'],
'impsumlorem' => ['pages.course.impsumlorem', '4'],
'loremimpsum' => ['pages.course.loremimpsum', '5'],
'loremloremimpsum' => ['pages.course.loremloremimpsum', '6'],
'impsumimpsomlorem' => ['pages.course.impsumimpsumlorem', '7'],
'looreem' => ['pages.course.looreem', '8'],
};
return view($view, [
'events' => Events::query()
->orderBy('title')
->orderBy('start')
->where('category', $id)
->where('start', '>', now())
->get()
]);
} catch (Throwable $e) {
// if no match was found return 404 error
abort(404);
}
}
So If I have for example this URL:
/events/289-loremimpsum-level2
and if this URL is not found in my DB it throws an Unhandled Match Case
I cannot do a default
because this would break the event page that the users get shown.
Users should get redirected with a error message to route name all-events
In my example above it does not even abort with a 404 error. I have no idea how to fix this issue for our users.
CodePudding user response:
You can throw exception in default like this and then catch the error:
[$view, $id] = match ($course) {
// URL Request from ($course) then the set the $view and $id
'lorem' => ['pages.course.lorem', '2'],
'impsum' => ['pages.course.impsum', '3'],
'impsumlorem' => ['pages.course.impsumlorem', '4'],
'loremimpsum' => ['pages.course.loremimpsum', '5'],
'loremloremimpsum' => ['pages.course.loremloremimpsum', '6'],
'impsumimpsomlorem' => ['pages.course.impsumimpsumlorem', '7'],
'looreem' => ['pages.course.looreem', '8'],
default => throw new \Exception('Not Found'),
};