Saturday, March 4, 2017

How do you check if a path is valid in Laravel 5?

I'm building a simple feature where you can pass a destination query parameter to the /login page that causes you to be redirected to that that page instead of the default behavior I have set.

The destination is stored in session and then used later to redirect inside of my LoginController.

Here is my snippet:

if ($destination = session('login_redirect')) { . 
    $route = app('router')->getRoutes()->match(app('request')->create($destination));
    $destination_route = route($route->getName(), $route->parameters());
}

I need to only redirect if the path is valid and I want to check that before deciding redirecting. By valid, I mean it's a URL that Laravel will return a 200 for. Right now when the path is valid I'm (logically) getting a NotFoundHttpException when I call app('request')->create() to turn the path into a route.

Is the only way to do some shenanigans in the render() function in app\Exceptions\Handler.php? If so, I'm not clear how to distinguish between a valid 404 (a user page request) and the exception I'm getting by creating a request programmatically.



via Justin

Advertisement