enriqg9 enriqg9 - 1 year ago 75
PHP Question

In Laravel, should I check for permission in controller if already checking on middleware?

I created a middleware that checks if the user is authorized to perform an action and added this middleware to the routes that I want to protect like this:

// VerifyPermission middleware

class VerifyPermission {

* Handle an incoming request.
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param $permission
* @return mixed
public function handle($request, Closure $next, $permission)
$user = auth()->user();

if (auth()->check() && $user->hasPermission($permission))
return $next($request);

return redirect('/');

// Routes

Route::patch('company/{id}', ['as' => 'updateCompany',
'uses' => 'SettingsController@updateCompany',
'middleware' => 'permission:manage_company']

My question is, is it necessary to make another check on
or is the middleware check sufficient?

public function updateCompany()
// Updates Company

return abort(403, "Unauthorized");

Answer Source

No, you should not make another check, the middleware will do it.

In fact handling authentication and permission handling is one of the most frequent uses for middleware

when you specify this:

Route::patch('company/{id}', ['as' => 'updateCompany',
                          'uses' => 'SettingsController@updateCompany',
                          'middleware' => 'permission:manage_company']

You're telling laravel that, when it finds a company/{id} route, it should trigger the handle method of the permission:manage_company middleware, before the request is sent to the SettingsController

So, when the request will get to your controller you're sure that it has satisfied all the middleware it went through

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download