Wes Murray Wes Murray - 28 days ago 7
PHP Question

Laravel: call global function for only authenticated users

I want to call a global function for only authenticated users to check if their account has been verified. From all routes

Function.

public function verifyAccount()
{
if (Auth::user()->verified == 0)
{
return redirect('/checkpoint');
}
return redirect('/home');
}


And that function is currently enabled in the base route.

Route::get('/', function () {
if (Auth::check()) {
UserService::verifyAccount();
}
return redirect('/home');
});


My problem is currently this only works for the home/base route. I was hoping there would be an easier way to implement for ALL routes without having to manually copy and paste to each route.

I would love to use the route group feature
['middleware' => 'auth']
to my routes. but i cant because the website allows for both guest and authenticated users.

any help would be appreciated.

Answer

You can create your own middleware inside app/Http/Middleware directory:

namespace App\Http\Middleware;

use Closure;

class VerifyAccount{

       public function handle($request, Closure $next) {
            if ($request->user()->verified) {
                return $next($request);
            } else {
                return response('Unauthorized.', 401);
                //////////// return redirect()->route('checkpoint');
            }
       }

}

Register your new middleware inside app/Http/Kernel.php:

protected $routeMiddleware = [
    ...
    ...
    'verifyAccount' => VerifyAccount::class
];

And using it in your routes.php:

Route::group(['middleware' => ['verifyAccount']], function () {
    //////////// Here all your routes

    ////// Example:
    Route::get('myProtectedRoute', array('uses' => 'MyController@MyControllerFunction'))->name('myActionName'); 
});


Isn't Laravel amazing? :-)

Comments