21

I want to guest users have access to home page but in built in authentication process laravel redirects to login page. how can i give guest users access to home page?

my routes.php:

Route::group(['middleware' => 'web'], function () {
Route::auth();

Route::get('/', 'HomeController@index');

Route::get('/insert', 'HomeController@insertform');
Route::get('/job/{id}', 'JobsController@show');

Route::get('/city/{city}', 'JobsController@city');

Route::post('/insert', 'HomeController@insert');
Route::get('/cityinsert', 'HomeController@cityinsert');
Route::post('/cityinsert', 'HomeController@cityinsertpost');

});

and authenticate.php

class Authenticate
{
 /**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @param  string|null  $guard
 * @return mixed
 */
public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->guest()) {
        if ($request->ajax()) {
            return response('Unauthorized.', 401);
        } else {
            return redirect()->guest('login');
        }
    }

    return $next($request);
}
}

and this is my kernel.php

class Kernel extends HttpKernel
{
/**
 * The application's global HTTP middleware stack.
 *
 * These middleware are run during every request to your application.
 *
 * @var array
 */
protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];

/**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],

    'api' => [
        'throttle:60,1',
    ],
];

/**
 * The application's route middleware.
 *
 * These middleware may be assigned to groups or used individually.
 *
 * @var array
 */
protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
}
masoud vali
  • 1,528
  • 2
  • 18
  • 29

7 Answers7

48

I prefer to exclude middleware via routes. You can do it in two ways:

  1. Single action:
Route::post('login', 'LoginController@login')->withoutMiddleware(['auth']);
  1. Group mode:
Route::group([
    'prefix' => 'forgot-password',
    'excluded_middleware' => ['auth'],
], function () {
    Route::post('send-email', 'ForgotPasswordController@sendEmail');
    Route::post('save-new-password', 'ForgotPasswordController@saveNewPassword');
});

Tested on Laravel 7.7

GetoX
  • 4,225
  • 2
  • 33
  • 30
  • +1 Excluding middleware in route is great because even if a middleware is added in constructor, it still won't let that register thus saves headache of tempering controller – Abdul Rehman Jul 09 '21 at 09:35
  • What a wonderful answer!! Thank you very much friend. I tested it here and it is possible to exclude middlewares and include them at the same time. – thiagobraga Sep 27 '21 at 21:41
  • 1
    As a side note, `withoutMiddleware()` method only available for Laravel 7.x and above. [Read this reference API](https://laravel.com/api/7.x/Illuminate/Routing/Route.html#method_withoutMiddleware) – ibnɘꟻ Nov 15 '21 at 02:47
  • That's not really a side note. The question is specifically "How to do this in Laravel 5.2". This answer does not work for the version in question. – DougW Mar 31 '22 at 17:20
33

Add an exception in the middleware declaration in the construct

Route::get('/', 'HomeController@index');

for the above route to be exempted from authentication you should pass the function name to the middleware like below

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth', ['except' => 'index']);
    }
}
Sidharth
  • 1,675
  • 1
  • 15
  • 23
12

Remove the middleware from HomeController construct:

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //$this->middleware('auth');
    }
}
Muhammet
  • 3,288
  • 13
  • 23
  • This is GREAT! now i get a message blocking my page that reads "You are logged in! " please help im going to pull my hair out. – Jp Silver Feb 11 '21 at 07:46
4

I can add to Sidharth answer, that you can use several methods exeption, by including them in array:

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth', ['except' => ['index', 'show']]);
    }
}

Laravel 5.5 tested.

Alex Sholom
  • 399
  • 4
  • 4
3

You can also separate between middleware and except. Try this one :

/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('guest')->except([
        'submitLogout',
        'showUserDetail'
    ]);
}

Tested on Laravel 5.4

ibnɘꟻ
  • 830
  • 13
  • 15
1

Add except URL to VerifyCsrfToken

app/http/middleware/VerifyCsrfToken.php
<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'stripe/*',
        'http://example.com/foo/bar',
        'http://example.com/foo/*',
    ];
}

Source: Laravel Documentation CSRF exclude URL

*Tested on Lavarel 7.0 as well

Mike
  • 493
  • 5
  • 14
0

Recently I need that functionality in an old Laravel project.

God bless Laravel for macroable feature :)

AppServiceProvider.php

public function boot()
    {
        Route::macro('withoutMiddleware', function ($excludedMiddlewares) {
            $this->action['middleware'] = array_filter(
                $this->action['middleware'],
                function ($middleware) use ($excludedMiddlewares) {
                    return !in_array($middleware, $excludedMiddlewares);
                });

            return $this;
        });
    }

Then you can use it like this:

Route::get('something')->withoutMiddleware(['auth']);
AmirRezaM75
  • 1,030
  • 14
  • 17