user148494
user148494

Reputation: 13

Laravel- 'auth' middleware not work

I use Laravel 5.6.33. I would like the user can have an access to the 'dashboard' page only when he/she has signed In/Up. When I use the 'guest' middleware, the user can't access the page at all and when I use the 'auth' middleware, the user always have an access to the page. What shall I do?

Route::group(['middleware' => ['web']], function (){
    Route::get('/dashboard', [
        'uses' => 'UserController@getDashboard',
        'as' => 'dashboard',
        'middleware' => 'auth'
    ]);
});

I have also added $this->middleware('auth'); in the getDashboard function or in the constructor of the UserController but it doesn't work. What shall I do?

In the Kernel.php the auth address is as follows:

 'auth' => \Illuminate\Auth\Middleware\Authenticate::class,

Upvotes: 1

Views: 15054

Answers (2)

CHARITRA SHRESTHA
CHARITRA SHRESTHA

Reputation: 782

you have to do nothing.

  • just add the following code.
    Route::group(['middleware'=>'auth'],function () {
    //you can create the list of the url or the resource here to block the unath users.
    Route::resource('brands', 'BrandController');
    Route::resource('products', 'ProductController');
    });

Or use the construct function on the controller which you want to block.

public function __construct()
{
    $this->middleware('auth');
}

it will block all the function on that controller like index, create, store, update, delete. only auth can use those functions.

Upvotes: 0

Alberto
Alberto

Reputation: 1408

If you are using Laravel 5.6 you don't need to wrap your routes with web middleware as long as you put them inside your routes\web.php file. Laravel makes this for you in the RouteServiceProvider.php.

For your purpose the auth middleware should work. Try this instead of what you have:

Route::middleware('auth')->group(function() {
  Route::get('/dashboard', [
    'uses' => 'UserController@getDashboard',
    'as' => 'dashboard'
  ]);
});

Upvotes: 2

Related Questions