Middleware
Middleware
Middleware provide a convenient mechanism for filtering HTTP requests entering your application. i.e, Yuga includes a middleware class that verifies whether the user of your application is authenticated.
Middleware
If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.
Of course, additional middleware can be written to perform a variety of tasks besides authentication.
There are several middleware that come with yuga-framework, including middleware for authentication and CSRF protection. App middleware are located in the app/Middleware
directory, but the ones that come with the framework are distributed across the entire framework depending on what they accomplish.
Defining Middleware
To create a new middleware, use the make:middleware
command:
This command will place a new CheckRoles
class within your app/Middleware
directory. In this middleware, we will only allow access to the route if the user accessing this route isadmin
. Otherwise, we will redirect the users back to the home
URI:
Assigning Middleware To Routes
If you would like to assign middleware to specific routes, you should first assign the middleware a key in your config/AppMiddleware
file. By default, the file comes with an array with only one middleware that comes with yuga, feel free to add as many as you want.
You can avoid this by using the command php yuga make:middleware TestMiddleware
and yuga will make TestMiddleware
lower cased without the word middleware and will push it to config/AppMiddleware
array for you.
Once the middleware has been defined in the config/AppMiddleware array, you can use it on a given route as below:
Last updated
Was this helpful?