Routing
Basic Routing
The most basic Laravel Hyperf routes accept a URI and a closure, providing a very simple and expressive method of defining routes and behavior without complicated routing configuration files:
use SwooleTW\Hyperf\Support\Facades\Route;
Route::get('/greeting', function () {
return 'Hello World';
});
The Default Route Files
All Laravel Hyperf routes are defined in your route files, which are located in the routes directory. These files are automatically loaded by your application's App\Providers\RouteServiceProvider. The routes/web.php file defines routes that are for your web interface. These routes are assigned the web middleware group. The routes in routes/api.php are stateless and are assigned the api middleware group.
For most applications, you will begin by defining routes in your routes/web.php file. The routes defined in routes/web.php may be accessed by entering the defined route's URL in your browser. For example, you may access the following route by navigating to http://example.com/user in your browser:
use App\Http\Controllers\UserController;
Route::get('/user', [UserController::class, 'index']);
Routes defined in the routes/api.php file are nested within a route group by the RouteServiceProvider. Within this group, the /api URI prefix is automatically applied so you do not need to manually apply it to every route in the file. You may modify the prefix and other route group options by modifying your RouteServiceProvider class.
Available Router Methods
The router allows you to register routes that respond to any HTTP verb:
Route::get($uri, $callback, $options);
Route::post($uri, $callback, $options);
Route::put($uri, $callback, $options);
Route::patch($uri, $callback, $options);
Route::delete($uri, $callback, $options);
Route::options($uri, $callback, $options);
Sometimes you may need to register a route that responds to multiple HTTP verbs. You may do so using the match method. Or, you may even register a route that responds to all HTTP verbs using the any method:
Route::match(['get', 'post'], '/', function () {
// ...
});
Route::any('/', function () {
// ...
});
Important
When defining multiple routes that share the same URI, routes using the get, post, put, patch, delete, and options methods should be defined before routes using the any and match methods. This ensures the incoming request is matched with the correct route.
Dependency Injection
You may type-hint any dependencies required by your route in your route's callback signature. The declared dependencies will automatically be resolved and injected into the callback by the Laravel service container. For example, you may type-hint the Illuminate\Http\Request class to have the current HTTP request automatically injected into your route callback:
use Hyperf\HttpServer\Request;
Route::get('/users', function (Request $request) {
// ...
});
The Route List
The route:list Artisan command can easily provide an overview of all of the routes that are defined by your application:
php artisan route:list
You may also instruct Laravel Hyperf to only show routes that begin with a given URI:
php artisan route:list --path=api
Route Parameters
Required Parameters
Sometimes you will need to capture segments of the URI within your route. For example, you may need to capture a user's ID from the URL. You may do so by defining route parameters:
Route::get('/user/{id}', function (string $id) {
return 'User '.$id;
});
You may define as many route parameters as required by your route:
Route::get('/posts/{post}/comments/{comment}', function (string $postId, string $commentId) {
// ...
});
Route parameters are always encased within "curly" braces. The parameters will be passed into your route's Closure when the route is executed.
Warning
Route parameters cannot contain the - character. Use an underscore (_) instead.
Parameters and Dependency Injection
If your route has dependencies that you would like the Laravel Hyperf service container to automatically inject into your route's callback, you should list your route parameters after your dependencies:
use Hyperf\HttpServer\Request;
Route::get('/user/{id}', function (Request $request, string $id) {
return 'User '.$id;
});
Optional Parameters
You may define optional route parameters by enclosing part of the route URI definition in [...]. So, for example, /foo[bar] will match both /foo and /foobar. Optional parameters are only supported in a trailing position of the URI. In other words, you may not place an optional parameter in the middle of a route definition:
Route::get('user[/{name}]', function ($name = null) {
return $name;
});
Regular Expression Constraints
You may constrain the format of your route parameters using the where method on a route instance. The where method accepts the name of the parameter and a regular expression defining how the parameter should be constrained:
Route::get('user/{name:[A-Za-z]+}', function ($name) {
//
});
Named Routes
Named routes allow the convenient generation of URLs or redirects for specific routes. You may specify a name for a route using the as array key when defining the route:
Route::get('profile', ['as' => 'profile', function () {
//
}]);
You may also specify route names for controller actions:
Route::get('profile', [
'as' => 'profile', 'uses' => 'UserController@showProfile'
]);
Important
Route names should always be unique.
Generating URLs to Named Routes
Once you have assigned a name to a given route, you may use the route's name when generating URLs or redirects via Laravel's route and redirect helper functions:
// Generating URLs...
$url = route('profile');
If the named route defines parameters, you may pass the parameters as the second argument to the route function. The given parameters will automatically be inserted into the URL in their correct positions:
Route::get('user/{id}/profile', ['as' => 'profile', function ($id) {
//
}]);
$url = route('profile', ['id' => 1]);
Route Groups
Route groups allow you to share route attributes, such as middleware or namespaces, across a large number of routes without needing to define those attributes on each individual route. Shared attributes are specified in an array format as the first parameter to the Route::group method.
To learn more about route groups, we'll walk through several common use-cases for the feature.
Middleware
To assign middleware to all routes within a group, you may use the middleware method before defining the group. Middleware are executed in the order they are listed in the array:
Route::group('api', function () {
Route::get('/', function () {
// Uses Auth Middleware
});
Route::get('user/profile', function () {
// Uses Auth Middleware
});
}, ['middleware' => 'auth']);
Route Model Binding
When injecting a model ID to a route or controller action, you will often query the database to retrieve the model that corresponds to that ID. Laravel Hyperf route model binding provides a convenient way to automatically inject the model instances directly into your routes. For example, instead of injecting a user's ID, you can inject the entire User model instance that matches the given ID.
Implicit Binding
Laravel Hyperf automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name. For example:
use App\Models\User;
Route::get('/users/{user}', function (User $user) {
return $user->email;
});
Since the $user variable is type-hinted as the App\Models\User Eloquent model and the variable name matches the {user} URI segment, Laravel Hyperf will automatically inject the model instance that has an ID matching the corresponding value from the request URI. If a matching model instance is not found in the database, a 404 HTTP response will automatically be generated.
Of course, implicit binding is also possible when using controller methods. Again, note the {user} URI segment matches the $user variable in the controller which contains an App\Models\User type-hint:
use App\Http\Controllers\UserController;
use App\Models\User;
// Route definition...
Route::get('/users/{user}', [UserController::class, 'show']);
// Controller method definition...
public function show(User $user)
{
return view('user.profile', ['user' => $user]);
}
Info
This feature is provided via SwooleTW\Hyperf\Router\Middleware\SubstituteBindings, and it's disabled by default. You can extend this middleware to customize your resolving behaviors.
Implicit Enum Binding
PHP 8.1 introduced support for Enums. To complement this feature, Laravel allows you to type-hint a string-backed Enum on your route definition and Laravel will only invoke the route if that route segment corresponds to a valid Enum value. Otherwise, a 404 HTTP response will be returned automatically. For example, given the following Enum:
<?php
namespace App\Enums;
enum Category: string
{
case Fruits = 'fruits';
case People = 'people';
}
You may define a route that will only be invoked if the {category} route segment is fruits or people. Otherwise, Laravel will return a 404 HTTP response:
use App\Enums\Category;
use SwooleTW\Hyperf\Support\Facades\Route;
Route::get('/categories/{category}', function (Category $category) {
return $category->value;
});
Throttling With Redis
Typically, the throttle middleware is mapped to the SwooleTW\Hyperf\Router\Middleware\ThrottleRequests class. This mapping is defined in your application's HTTP kernel (App\Http\Kernel). However, if you are using Redis as your application's cache driver, you may wish to change this mapping to use the Illuminate\Routing\Middleware\ThrottleRequestsWithRedis class. This class is more efficient at managing rate limiting using Redis:
'throttle' => \SwooleTW\Hyperf\Router\Middleware\ThrottleRequests::class,