Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Randy_Johnson's avatar

Middleware on specific Methods

I have run into a problem where I have multiple users using different functions in one Controller, the problem is that a standard user can have access to a controller that has admin functionality. I did this because I thought I can get away with having to create multiple of the same controllers.

The problem is I don't want a standard user running admin functionality from that controller, so I was wondering if I can put restrictions with middleware on a specific method.

D:.
│   Controller.php
│   WelcomeController.php
│
├───Auth
│       ConfirmPasswordController.php
│       ForgotPasswordController.php
│       LoginController.php
│       RegisterController.php
│       ResetPasswordController.php
│       VerificationController.php
│
├───Dashboard
│       AdminController.php
│       AttendanceController.php
│       CustodialController.php
│       FeeController.php
│       GradeController.php
│       ImageController.php
│       InjuryController.php
│       PaymentController.php
│       PermissionController.php
│       ReportController.php
│       RoleController.php
│       StudentController.php
│       SubjectController.php
│       TeacherController.php
│       TimeTableController.php
│       UserController.php
│
└───Tools
        MailController.php
        MessageAlertController.php
        MessageController.php
0 likes
2 replies
chaudigv's avatar
chaudigv
Best Answer
Level 16

You can create middleware for this.

php artisan make:middleware EnsureUserIsAdmin

Register your middleware in app/Http/Kernel.php

protected $routeMiddleware = [
	.
	.
	'EnsureUserIsAdmin' => \App\Http\Middleware\EnsureUserIsAdmin::class,
]

In the handle() method

public function handle($request, Closure $next) {
	abort_unless(Auth::user()->is_admin, 401); // use appropriate column name
	return $next($request);
}

Middleware on specific methods:

class AttendanceController extends Controller
{
    /**
     * Instantiate a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('EnsureUserIsAdmin'); // apply to all methods
        $this->middleware('EnsureUserIsAdmin')->only(['index']); // apply on only given methods
        $this->middleware('EnsureUserIsAdmin')->except(['store']); // apply on all methods except the given methods
    }
}
2 likes

Please or to participate in this conversation.