Skip to content

Instantly share code, notes, and snippets.

@juampi92
Created November 7, 2019 10:02
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save juampi92/fff250719122a596c716c64e5b0afef6 to your computer and use it in GitHub Desktop.
Save juampi92/fff250719122a596c716c64e5b0afef6 to your computer and use it in GitHub Desktop.
Build Requests with routes on Laravel for testing.
<?php
use Illuminate\Http\Request;
use Illuminate\Routing\Route;
use Illuminate\Support\Facades\Route as Router;
class RequestBuilder
{
/**
* Will create a request with the correct fullUrl, route parameters and input parameters.
*
* @example RequestBuilder::create('post.show', ['postId' => 1], PostShowRequest::class);
* @example RequestBuilder::create('post.index');
*
* @param string $routeName Name of the route.
* @param array $parameters Array of route or input parameters.
* @param string $class Request class.
* @throws \Exception If the route name doesn't exist.
* @return Request
*/
public static function create(string $routeName, array $parameters = [], string $class = Request::class)
{
// Find the route properties.
$route = Router::getRoutes()->getByName($routeName);
throw_if(is_null($route), new \Exception("[RequestBuilder] Couldn't find route by the name of {$routeName}."));
// Recreate the full url
$fullUrl = route($routeName, $parameters);
$method = $route->methods()[0];
$uri = $route->uri;
$request = $class::create($fullUrl);
$request->setRouteResolver(function () use ($request, $method, $uri) {
// Associate Route to request so we can access route parameters.
return (new Route($method, $uri, []))->bind($request);
});
return $request;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment