Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

laidbackwebsage's avatar

Solved: Show non-authenticated routes regardless of authentication

I am new to Laravel, so I am probably missing something basic, but I can't get this to work the way I want, so here I am.

First, I understand that Laravel's default functionality is that, no matter what, if the user is not authenticated, the user is redirected to the login page, and, after successful authentication, is redirected to "/home". I do not want this functionality at all.

Instead, what I want is a set of pages that require authentication, and another set where it doesn't matter if the user is logged in or not. In other words, a User lands on "/" and gets a regular, plain ol' vanilla Laravel page that requires absolutely no authentication to see. There are links to other pages on the siiite that also do not require any authentication.

Then, the user logs in. The user is still on the page from which the user logged in from. Now, the only difference between the page pre-login and post-login is that the "login" form and the "register" link for non-autheticated users have been replaced by a dropdown of actions and links available for logged in users. Trying to get to any of these resources while unautheticated, will result in an error message asking the user to login or register.

Here is my web.php file :

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Auth::routes();

Route::group(['middleware' => 'guest'], function () {
    Route::get('/', 'HomeController@index')->name('home');
    Route::get('/about', 'HomeController@about')->name('about');
    Route::get('/contact', 'HomeController@contact')->name('contact');
    Route::get('logout', ['as' => 'logout', 'uses' => 'Auth\LoginController@logout']);
});

Route::prefix('dashboard')->group(function () {
    Route::get('/', 'DashboardController@index')->name('dashboard');
    Route::get('settings', 'DashboardController@settings')->name('dashboard.settings');
    Route::get('profile', 'DashboardController@profile')->name('dashboard.profile');
    Route::get('help', 'DashboardController@help')->name('dashboard.help');
    Route::post('search', 'DashboardController@search')->name('dashboard.search');
});

Route::prefix('admin')->group(function () {
    Route::get('/', 'AdminController@index')->name('admin.home');
    Route::resource('users', 'UserController');
    Route::resource('roles', 'RoleController');
    Route::resource('permissions', 'PermissionController');
});

Here is the result of php artisan route:list:

+--------+-----------+-------------------------------------+---------------------+------------------------------------------------------------------------+------------------+
| Domain | Method    | URI                                 | Name                | Action                                                                 | Middleware       |
+--------+-----------+-------------------------------------+---------------------+------------------------------------------------------------------------+------------------+
|        | GET|HEAD  | /                                   | home                | App\Http\Controllers\HomeController@index                              | web,guest        |
|        | GET|HEAD  | about                               | about               | App\Http\Controllers\HomeController@about                              | web,guest        |
|        | GET|HEAD  | admin                               | admin.home          | App\Http\Controllers\AdminController@index                             | web,auth,isAdmin |
|        | POST      | admin/permissions                   | permissions.store   | App\Http\Controllers\PermissionController@store                        | web,auth,isAdmin |
|        | GET|HEAD  | admin/permissions                   | permissions.index   | App\Http\Controllers\PermissionController@index                        | web,auth,isAdmin |
|        | GET|HEAD  | admin/permissions/create            | permissions.create  | App\Http\Controllers\PermissionController@create                       | web,auth,isAdmin |
|        | DELETE    | admin/permissions/{permission}      | permissions.destroy | App\Http\Controllers\PermissionController@destroy                      | web,auth,isAdmin |
|        | PUT|PATCH | admin/permissions/{permission}      | permissions.update  | App\Http\Controllers\PermissionController@update                       | web,auth,isAdmin |
|        | GET|HEAD  | admin/permissions/{permission}      | permissions.show    | App\Http\Controllers\PermissionController@show                         | web,auth,isAdmin |
|        | GET|HEAD  | admin/permissions/{permission}/edit | permissions.edit    | App\Http\Controllers\PermissionController@edit                         | web,auth,isAdmin |
|        | POST      | admin/roles                         | roles.store         | App\Http\Controllers\RoleController@store                              | web,auth,isAdmin |
|        | GET|HEAD  | admin/roles                         | roles.index         | App\Http\Controllers\RoleController@index                              | web,auth,isAdmin |
|        | GET|HEAD  | admin/roles/create                  | roles.create        | App\Http\Controllers\RoleController@create                             | web,auth,isAdmin |
|        | PUT|PATCH | admin/roles/{role}                  | roles.update        | App\Http\Controllers\RoleController@update                             | web,auth,isAdmin |
|        | GET|HEAD  | admin/roles/{role}                  | roles.show          | App\Http\Controllers\RoleController@show                               | web,auth,isAdmin |
|        | DELETE    | admin/roles/{role}                  | roles.destroy       | App\Http\Controllers\RoleController@destroy                            | web,auth,isAdmin |
|        | GET|HEAD  | admin/roles/{role}/edit             | roles.edit          | App\Http\Controllers\RoleController@edit                               | web,auth,isAdmin |
|        | POST      | admin/users                         | users.store         | App\Http\Controllers\UserController@store                              | web,auth,isAdmin |
|        | GET|HEAD  | admin/users                         | users.index         | App\Http\Controllers\UserController@index                              | web,auth,isAdmin |
|        | GET|HEAD  | admin/users/create                  | users.create        | App\Http\Controllers\UserController@create                             | web,auth,isAdmin |
|        | GET|HEAD  | admin/users/{user}                  | users.show          | App\Http\Controllers\UserController@show                               | web,auth,isAdmin |
|        | PUT|PATCH | admin/users/{user}                  | users.update        | App\Http\Controllers\UserController@update                             | web,auth,isAdmin |
|        | DELETE    | admin/users/{user}                  | users.destroy       | App\Http\Controllers\UserController@destroy                            | web,auth,isAdmin |
|        | GET|HEAD  | admin/users/{user}/edit             | users.edit          | App\Http\Controllers\UserController@edit                               | web,auth,isAdmin |
|        | GET|HEAD  | api/user                            |                     | Closure                                                                | api,auth:api     |
|        | GET|HEAD  | contact                             | contact             | App\Http\Controllers\HomeController@contact                            | web,guest        |
|        | GET|HEAD  | dashboard                           | dashboard           | App\Http\Controllers\DashboardController@index                         | web,auth         |
|        | GET|HEAD  | dashboard/help                      | dashboard.help      | App\Http\Controllers\DashboardController@help                          | web,auth         |
|        | GET|HEAD  | dashboard/profile                   | dashboard.profile   | App\Http\Controllers\DashboardController@profile                       | web,auth         |
|        | POST      | dashboard/search                    | dashboard.search    | App\Http\Controllers\DashboardController@search                        | web,auth         |
|        | GET|HEAD  | dashboard/settings                  | dashboard.settings  | App\Http\Controllers\DashboardController@settings                      | web,auth         |
|        | GET|HEAD  | login                               | login               | App\Http\Controllers\Auth\LoginController@showLoginForm                | web,guest        |
|        | POST      | login                               |                     | App\Http\Controllers\Auth\LoginController@login                        | web,guest        |
|        | POST      | logout                              | logout              | App\Http\Controllers\Auth\LoginController@logout                       | web              |
|        | GET|HEAD  | logout                              | logout              | App\Http\Controllers\Auth\LoginController@logout                       | web,guest        |
|        | POST      | password/email                      | password.email      | App\Http\Controllers\Auth\ForgotPasswordController@sendResetLinkEmail  | web,guest        |
|        | POST      | password/reset                      |                     | App\Http\Controllers\Auth\ResetPasswordController@reset                | web,guest        |
|        | GET|HEAD  | password/reset                      | password.request    | App\Http\Controllers\Auth\ForgotPasswordController@showLinkRequestForm | web,guest        |
|        | GET|HEAD  | password/reset/{token}              | password.reset      | App\Http\Controllers\Auth\ResetPasswordController@showResetForm        | web,guest        |
|        | POST      | register                            |                     | App\Http\Controllers\Auth\RegisterController@register                  | web,guest        |
|        | GET|HEAD  | register                            | register            | App\Http\Controllers\Auth\RegisterController@showRegistrationForm      | web,guest        |
+--------+-----------+-------------------------------------+---------------------+------------------------------------------------------------------------+------------------+

Here is the middleware list fromKernel.php:

/**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'isAdmin' => \App\Http\Middleware\AdminMiddleware::class,
    ];

And here is the AdminMiiiddleware:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;
use App\User;

class AdminMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $user = User::all()->count();
        if (!($user == 1)) {
            if (!Auth::user()->hasPermissionTo('Administer roles & permissions')) { //If user does //not have this permission
                abort('401');
            }
        }

        return $next($request);
    }
}

I started with the default php artisan make:auth. I added spatie/laravel-permission for roles and permissions.

I would greatly appreciate any hand-holding someone can provide.

Thanks in advance. :-)

0 likes
3 replies
pawelmysior's avatar

First, I understand that Laravel's default functionality is that, no matter what, if the user is not authenticated, the user is redirected to the login page, and, after successful authentication, is redirected to "/home". I do not want this functionality at all.

That's not exactly accurate. The routes that you define in routes/web.php are be default accessible by anyone, authenticated or not.

If you want a specific route to be accessible only by authenticated users you need to apply the auth middleware to it. Like so:

Route::get('dashboard', 'DashboardController@index')->middleware('auth');

Or if you wan't it for multiple routes, do this:

Route::middleware('auth')->prefix('dashboard')->group(function () {
    Route::get('/', 'DashboardController@index')->name('dashboard');
    Route::get('settings', 'DashboardController@settings')->name('dashboard.settings');
    Route::get('profile', 'DashboardController@profile')->name('dashboard.profile');
    Route::get('help', 'DashboardController@help')->name('dashboard.help');
    Route::post('search', 'DashboardController@search')->name('dashboard.search');
});

You can also structure it like this:

Route::middleware('auth')->group(function () {
    Route::prefix('dashboard')->group(function () {
        // ...
    });

    Route::prefix('admin')->group(function () {
        // ...
    });
});

The guest middleware acts in the exact opposite way. It will allow only unauthenticated users to view the route. Normally I would say that only the login and register routes should have this middleware.

laidbackwebsage's avatar

Here is my web.php file, now:

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Auth::routes();

Route::group([], function () {
    Route::get('/', 'HomeController@index')->name('home');
    Route::get('/about', 'HomeController@about')->name('about');
    Route::get('/contact', 'HomeController@contact')->name('contact');
    Route::get('logout', ['as' => 'logout', 'uses' => 'Auth\LoginController@logout']);
});

Route::middleware('auth')->prefix('dashboard')->group(function () {
    Route::get('/', 'DashboardController@index')->name('dashboard');
    Route::get('settings', 'DashboardController@settings')->name('dashboard.settings');
    Route::get('profile', 'DashboardController@profile')->name('dashboard.profile');
    Route::get('help', 'DashboardController@help')->name('dashboard.help');
    Route::post('search', 'DashboardController@search')->name('dashboard.search');
});

Route::middleware('auth')->prefix('admin')->group(function () {
    Route::get('/', 'AdminController@index')->name('admin.home');
    Route::resource('users', 'UserController');
    Route::resource('roles', 'RoleController');
    Route::resource('permissions', 'PermissionController');
});

Please or to participate in this conversation.