Middleware is a way to filter HTTP requests entering your application.
Middleware can be assigned to routes or controller actions to perform tasks such as authentication, logging, or modifying the request or response.
To use middleware in a Laravel controller, you can apply middleware directly to the controller or to specific controller methods (actions).
1. Middleware on Controller Constructor:
You can apply middleware to all methods within a controller by adding it to the controller's constructor.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class YourController extends Controller
{
public function __construct()
{
$this->middleware('middleware-name');
}
// Your controller methods...
}
?>
2.Middleware on Specific Controller Method:
If you only want to apply middleware to specific methods within the controller, you can use the middleware method directly on the method.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class YourController extends Controller
{
public function yourMethod()
{
$this->middleware('middleware-name');
// Your method logic...
}
// Other controller methods...
}
?>
3.Middleware in Route Definition:
Alternatively, you can apply middleware directly in your route definition in the web.php or api.php file.
<?php
use App\Http\Controllers\YourController;
Route::get('/your-route', [YourController::class, 'yourMethod'])
->middleware('middleware-name');
?>
This approach allows you to apply middleware on a per-route basis.
Remember to replace 'middleware-name' with the actual name of the middleware you want to apply.
Also, ensure that the middleware is registered in the $routeMiddleware property of the app/Http/Kernel.php file.