Ad

Laravel Middleware 'except' Rule Not Working

- 1 answer

I have a controller with the following in the constructor:

$this->middleware('guest', ['except' =>
    [
        'logout',
        'auth/facebook',
        'auth/facebook/callback',
        'auth/facebook/unlink'
    ]
]);

The 'logout' rule (which is there by default) works perfectly but the other 3 rules I have added are ignored. The routes in routes.php look like this:

Route::group(['middleware' => ['web']],function(){

    Route::auth();

    // Facebook auth
    Route::get('/auth/facebook', 'Auth\[email protected]')->name('facebook_auth');
    Route::get('/auth/facebook/callback', 'Auth\[email protected]')->name('facebook_callback');
    Route::get('/auth/facebook/unlink', 'Auth\[email protected]')->name('facebook_unlink');
}

If I visit auth/facebook, auth/facebook/callback or auth/facebook/unlink whilst logged in I get denied by the middleware and thrown back to the homepage.

I've tried specifying the 'except' rules with proceeding /'s so they match the routes in routes.php exactly but it makes no difference. Any ideas why these rules are being ignored, whilst the default 'logout' rule is respected?

Cheers!

Ad

Answer

You need to pass the method's name instead of the URI.

<?php
    
namespace App\Http\Controllers;
    
class MyController extends Controller {
    public function __construct() {
        $this->middleware('guest', ['except' => [
            'redirectToFacebook', 'handleFacebookCallback', 'handleFacebookUnlink'
        ]]);
    }
}

Since Laravel 5.3, you can use fluent interface to define middlewares on controllers, which seems cleaner than using multidimensional arrays.

<?php

$this->middleware('guest')->except('redirectToFacebook', 'handleFacebookCallback', 'handleFacebookUnlink');
Ad
source: stackoverflow.com
Ad