Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #202
    dan
    Participant

    At first glance, they Laravel middleware and gates functions the same. But I’m they are not created to the same exact things? My question is what’s the difference between middleware and gates?

    #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

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.