#203

For it me it looks they do the same thing. For example, gates can also be used to filter http request inside a controller by denying the user before a route direct.

In Laravel, the difference is where they are being used. For example, Middleware works in routes and controller while gates is used inside a controller and in blade files.

Middleware:
It can work on routes and controller.

If you put on the route like this for example

Route::get(‘/posts’, [PostController::class, ‘index’])-middleware(‘auth’);

Then non-authenticated user cant access the page /posts

If you define it in controller like this

public function __construct() {
// Apply the auth middleware to every function in this controller
$this-;middleware(‘auth’);

}

This means only authenticated user can perform all the methods specified on that controller
Gates:

Gates can work inside the controller like this.

public function delete(Request $request, Post $post)
{
if (Gate::denies(‘delete-post’, $post)) { // Returns true if $post->user_id is not the same as `$user-
>id` (a.k.a the user is not allowed to delete this post)
abort(403);
}

$post->delete();
}

Gates can also work inside a blade template:

@can(‘delete-post’, $post)
<!– Show a link to the delete page here –>
@endcan