Skip to content

Commit 611a8c0

Browse files
committed
feat: add docs on __middleware
1 parent f2db5b2 commit 611a8c0

File tree

1 file changed

+36
-0
lines changed
  • src/docs/routing/middleware

1 file changed

+36
-0
lines changed

src/docs/routing/middleware/mvc.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,42 @@ class MyController extends Controller
161161

162162
Once the data is read using `request()->next()`, it is removed from the request object and cannot be accessed again during the request lifecycle.
163163

164+
## Controller Middleware <Badge>New</Badge>
165+
166+
The middleware we have seen so far is applied to routes, which is great for most use-cases. However, there are times when you may want to apply middleware to one or more controller methods, instead of individual routes. This is especially useful when you have an application which has both web and API routes, and you want to apply different middleware to each. To use this, find the controller you want to add middleware to, and add a `__middleware` method to it:
167+
168+
```php
169+
<?php
170+
171+
namespace App\Controllers\Mobile;
172+
173+
/**
174+
* This is a base controller for the mobile namespace
175+
*/
176+
class Controller extends \App\Controllers\Controller
177+
{
178+
public function __middleware()
179+
{
180+
auth()->config('session', false);
181+
182+
if (!auth()->user()) {
183+
response()->json([
184+
'success' => false,
185+
'message' => 'Unauthorized',
186+
], 401);
187+
188+
return false;
189+
}
190+
191+
return true;
192+
}
193+
}
194+
```
195+
196+
In this example, we have a base controller for the `Mobile` namespace, which contains all controllers for our mobile API. The `__middleware` method disables session auth, meaning all authentication will be done using API tokens (JWTs), and then returns a JSON response if the user is not authenticated. Since this is a base controller, all controllers in the `Mobile` namespace will inherit this middleware which means all routes in this namespace will require authentication.
197+
198+
Unlike the route middleware, the controller middleware returns a boolean value. If it returns `true`, the request will continue to the next step (either another middleware or the controller method). If it returns `false`, the request will stop and no further processing will be done.
199+
164200
## What to read next
165201

166202
Middleware is a powerful tool that can help you control the flow of requests in your application, but Leaf already has a lot of functionality built-in that you might not need to write your own middleware for. Check out some of the other features of Leaf & Leaf MVC:

0 commit comments

Comments
 (0)