php - advanced authentication routes in laravel 5

309

i currently have /dashboard route that is behind login page, which after login takes you to admin panel.

Route::get('dashboard', ['middleware' => 'auth', function()
{
    return view('dash.dashboard');
}]);

this is working fine. But I can't figure out how to prevent access to all the links in admin panel if not logged in. how can i prevent all the dashboard/{} routes? note - I'm still learning laravel.

71

Answer

Solution:

You can use Route::group() to wrap all your admin routes and make them use the auth middleware, example :

Route::group(['middleware' => ['foo', 'bar']], function()
{
    Route::get('/', function()
    {
        // Has Foo And Bar Middleware
    });

    Route::get('user/profile', function()
    {
        // Has Foo And Bar Middleware
    });

});

See more in the documentation

444

Answer

Solution:

What you can do is, you can create a controller, let's sayDashboardController and create a route, like the following:

$router->get('dashboard', '[email protected]');
// calling the index function of your DashboardController

And in yourDashboardController, do this in your constructor:

class DashboardController extends BaseController
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        return view('dash.dashboard');
    }
}

Create other functions in this controller, so everytime, the functions in this controller are called, it will check the auth middleware. This is a good way to do it.

The other way to do it is to use route group.

 $router->group(['middleware' => 'auth'], function() {
     $router->get('dashboard', function(){
         return view('dash.dashboard');
     });
 });

People are also looking for solutions to the problem: javascript - Why blocking direct url access also demolishes Ajax call from a file on the webserver?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.