diff --git a/src/Illuminate/Routing/Router.php b/src/Illuminate/Routing/Router.php index d13ce249cfa9..a392acb41c49 100644 --- a/src/Illuminate/Routing/Router.php +++ b/src/Illuminate/Routing/Router.php @@ -572,20 +572,7 @@ public function dispatch(Request $request) */ public function dispatchToRoute(Request $request) { - // First we will find a route that matches this request. We will also set the - // route resolver on the request so middlewares assigned to the route will - // receive access to this route instance for checking of the parameters. - $route = $this->findRoute($request); - - $request->setRouteResolver(function () use ($route) { - return $route; - }); - - $this->events->dispatch(new Events\RouteMatched($route, $request)); - - $response = $this->runRouteWithinStack($route, $request); - - return $this->prepareResponse($request, $response); + return $this->buildResponse($request, $this->findRoute($request)); } /** @@ -603,6 +590,26 @@ protected function findRoute($request) return $route; } + /** + * Return the response for the given route. + * + * @param Route $route + * @param Request $request + * @return mixed + */ + protected function buildResponse(Request $request, Route $route) + { + $request->setRouteResolver(function () use ($route) { + return $route; + }); + + $this->events->dispatch(new Events\RouteMatched($route, $request)); + + return $this->prepareResponse($request, + $this->runRouteWithinStack($route, $request) + ); + } + /** * Run the given route within a Stack "onion" instance. * @@ -1102,6 +1109,19 @@ public function auth() $this->post('password/reset', 'Auth\ResetPasswordController@reset'); } + /** + * Return a response out of the given route. + * + * @param string $name + * @return mixed + */ + public function respondWith($name) + { + return $this->buildResponse($this->currentRequest, + tap($this->routes->getByName($name))->bind($this->currentRequest) + ); + } + /** * Set the unmapped global resource parameters to singular. * diff --git a/tests/Integration/Routing/FallbackRouteTest.php b/tests/Integration/Routing/FallbackRouteTest.php index cf85a9d26fec..a5d05c844405 100644 --- a/tests/Integration/Routing/FallbackRouteTest.php +++ b/tests/Integration/Routing/FallbackRouteTest.php @@ -72,6 +72,20 @@ public function test_no_routes() $this->assertEquals(404, $this->get('/non-existing')->getStatusCode()); } + public function test_respond_with_named_fallback_route() + { + Route::fallback(function () { + return response('fallback', 404); + })->name('testFallbackRoute'); + + Route::get('one', function () { + return Route::respondWith('testFallbackRoute'); + }); + + $this->assertContains('fallback', $this->get('/non-existing')->getContent()); + $this->assertContains('fallback', $this->get('/one')->getContent()); + } + public function test_no_fallbacks() { Route::get('one', function () {