skip to Main Content

I am using laravel 5.7. Please see my code:

web.php

Route::prefix('admin')->group(function () {
        Route::get('/', function () {
           return redirect()->route('admin.check');
       });
Route::get('/check-auth', 'AdminAdminController@checkAuth')->name('admin.check');
});

AdminController::checkAuth()

public function checkAuth()
    {
        if(true == Auth::guard('admin')->user()){
            return redirect()->route('cs.dashboard');
        } else{
            return redirect()->route('admin.login');
        }
    }

I have created a group of routes with prefix admin.

What I need is, when I use url localhost:8000/admin then it should check Auth of admin user, if user is logged in then it should show admin dashboard otherwise redirect him to admin login page : localhost:8000/admin/login but the issue over here is I am getting apache error which reads:

Not Found
The requested resource /admin was not found on this server.

I also tried using htaccess file placing it in root/public/admin location, it somewhat solved my issue but I have to use this url.

localhost:8000/index.php/admin

and I dont need index.php in my url.

This is what my .htaccess file looks:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

Please help me to resolve it.

2

Answers


  1. Normal way to check if user is authenticated is Middleware

    In your case, check-auth runs when you go to: localhost:8000/admin/ or localhost:8000/admin/check-auth othwewise laravel will not check authentication.

    Please look at Laravel Middlewares.

    Login or Signup to reply.
  2. I think that the best way is using Middleware to check if the logged in user is admin or not.. and it will make your code more elegant than now..
    You only need to make the middleware to check if it’s admin or not.. if it’s admin then return $next($request), if not redirect to other page..
    Then change your code..

     Route::prefix('admin')->group(function () {
            Route::get('/', 'AdminController@index');
    });
    

    Then create the admin controller and add index function like

    public function __construct()
    {
        $this->middleware('admin');
    }
    
    public function index()
    {
        return view('adminpage');
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search