How to restrict routes or url in laravel 5.7 to each user?

0

Hello, I have recently been learning laravel but reading the documentation I can not understand the authentication part and this happens in the part of restricting routes to users. For example, if I have an administrator user who can enter these routes:

  • mipagina.com/registrar-product
  • mipagina.com/edit-product
  • mipagina.com/gestion-product

Another client user who can see the products and buy

  • mipagina.com/listado-de-productos

  • mipagina.com/buy-products

How would you make the client user unable to access the administrator's routes? I just need some theories or points to start investigating since I feel confused with this part. I managed to make a login but any logged in user can access all the routes

    
asked by Luis Hernandez 05.12.2018 в 17:05
source

2 answers

1

As you mentioned before, it is best to use a group, but in addition to that, it is also good that you add an alias, a namespace and a specific middleware to validate the admin.

All this because generally the controllers and routes of the admin must be separated from the user routes, and the middleware because the user admin is validated different from the normal user

Everything should be more or less like this

Route::namespace('Admin')
     ->prefix('admin')
     ->name('admin.')
     ->middleware(['auth', 'admin'])
     ->group(function () 
    {
      /*
      Route::get('/', function () {
          // 
      });
      */   
    });

In this way all the routes are like this:

mipagina.com/admin/registrar-product the admin is added in an "automatic" way

The names of the routes are as follows:

admin.registerProduct

And the path of the controllers like this:

App \ Http \ Controllers \ Admin

Remember that you must create the middleware here you can find the documentation about it link

Here you can find an interesting article about it Laravel Route Tips to Improve Your Routing

    
answered by 05.12.2018 / 17:39
source
2

You do not specify the version of laravel, but in any case, the groups of routes are the most appropriate. ( link )

Example of routes for admin exclusively:

Route::group(['prefix' => 'admin',  'middleware' => 'auth'], function() {
    /*
    Route::get('/', function () {
        // 
    });
    */   
});

Greetings

    
answered by 05.12.2018 в 17:15