D
D
DocTypeMaster2021-02-19 23:16:26
Laravel
DocTypeMaster, 2021-02-19 23:16:26

How to restrict access in laravel?

Hello, there is a site on laravel and there is a database of users in the fields of which there is “status” and it can be either a user or an admin. By the way, I have a breeze package.

And there are pages and, in general, a separate admin layout (admin panel), but everyone can go to it, I did such a thing that I checked the status in the file with routes and displayed this return for a specific route, but it’s not convenient to do this because it will have to be for all routes separately, and it does not remove access, but only hides the view, tell me how to do those you and how to do it right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jazzus, 2021-02-20
@jazzus

Authorization can be correctly checked through authorization rules
Create a new route file routes/admin/web.php. Copy all admin routes there.
We write the rule in the boot AuthServiceProvider method

Gate::define('view-admin', function (User $user) {
    return $user->is_admin;
});

We connect admin routes with access restriction in the boot RouteServiceProvider method
Route::middleware(['web', 'can:view-admin'])
    ->namespace($this->namespace)
    ->group(base_path('routes/admin/web.php'));

Now, before each request of the admin route, a check will be performed. The same rule will work in templates, for example, to hide a button.
@can('view-admin')
  кнопка
@endcan

or in logic
if ($user->can('view-admin')) {
    // code
}

which is impossible to do without shitcode if you use only the middleware, as suggested.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question