I want to create a custom middleware that runs only if the user is authenticated and the email is a specific email address to access the / admin page.
Although, when I point out my custom route and then redirect it, it always says too many redirects.
A brief explanation.
- User login → redirected to / home. (Works)
- If the user is trying to access / admin and their email address is not the same as the one specified in the middleware, redirect to / home.
- If true, let them in / admin
My middleware is called admin.verify
The routes file is automatically loaded, and if I redirect ('/ home'), it automatically launches my middleware, so I assume that it redirects too often to the main page.
Route File:
Route::get('/admin', 'AdminController@index')->name('admin.index');
AdminController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AdminController extends Controller
{
public function __construct(){
$this->middleware(['auth', 'admin.verify']);
}
public function index(){
return view('admin.test');
}
}
Middleware:
public function handle($request, Closure $next)
{
if (Auth::check() && Auth::User()->email == 'Tester@gmail.com') {
return $next($request);
} else {
return redirect()->route('home');
}
My home route:
GET|HEAD | home | home| App\Http\Controllers\HomeController@index | web,auth
Home controller:
class HomeController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
return view('home');
}
}
source
share