1

I am trying to redirect the unauthorized user to login page. But the problem is i delete the auth folder in the view, it redirect me to the auth.login page. I want to redirect me to the local host main URL (http://127.0.0.1:8000/). How to resolve it?

web.php

<?php

use Illuminate\Support\Facades\Route;

Auth::routes();


Route::prefix('/admin')->namespace('Admin')->group(function () {

    Route::get('/', [App\Http\Controllers\Admin\AdminController::class, 'login']);
    Route::group(['middleware' => ['admin']], function () {
        Route::match(['get', 'post'], 'dashboard', [App\Http\Controllers\Admin\AdminController::class, 'dashboard']);
    });
});


Route::namespace('Front')->group(function () {
    //Home Page Route
    Route::get('/', [App\Http\Controllers\Front\IndexController::class, 'login']);
    Route::post('login', [App\Http\Controllers\Front\IndexController::class, 'userlogin']);
    Route::get('userRegister', [App\Http\Controllers\Front\IndexController::class, 'register']);
    Route::post('user-register', [App\Http\Controllers\Front\IndexController::class, 'userRegister']);

    // Middleware
    Route::group(['middleware' => ['auth']], function () {
        Route::match(['get', 'post'], 'studentdashboard', [App\Http\Controllers\Front\IndexController::class, 'dashboard']);
        Route::get('studentlogout', [App\Http\Controllers\Front\IndexController::class, 'logout']);
    });
});
  • When unauthorized user trying to access the files the system should redirect the to IndexController login function

1 Answer 1

0

just edit app\Exceptions\Handler.php

public function render($request, Exception $e)
{
  //if unautorized
    if ($e instanceof AuthorizationException) {
        return redirect('/');
    }

 //or if path/file is not found:
  if ($e instanceof NotFoundHttpException) {
        return redirect('/');
    }

    return parent::render($request, $e);
}

dont forget to use the classes:

use Illuminate\Auth\AuthenticationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

or if you have custom auth middleware you can add that on you middleware too

Sign up to request clarification or add additional context in comments.

1 Comment

on return parent::render($request, $e); it gives an error Cannot use 'parent' in a class with no parent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.