PHPackages                             mnabialek/laravel-authorize - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. mnabialek/laravel-authorize

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

mnabialek/laravel-authorize
===========================

Allows authorize user based on role or permission

v1.2.2(8y ago)03141MITPHP

Since Mar 6Pushed 8y ago1 watchersCompare

[ Source](https://github.com/mnabialek/laravel-authorize)[ Packagist](https://packagist.org/packages/mnabialek/laravel-authorize)[ RSS](/packages/mnabialek-laravel-authorize/feed)WikiDiscussions master Synced 3w ago

READMEChangelog (6)Dependencies (1)Versions (10)Used By (0)

Laravel Authorize
=================

[](#laravel-authorize)

This module makes managing user access to different parts of **Laravel** applications easier. You can protect your routes with `authorize` middleware based on **user roles or user permissions** without adding any extra code to your controller to keep them as clean as no authorization were used at all.

Supported versions
------------------

[](#supported-versions)

To install in Laravel **5.4+** use this branch, however to install in Laravel &gt;= 5.1 and Laravel &lt; 5.4 please refer to [version 1.1](https://github.com/mnabialek/laravel-authorize/tree/1.1).

Installation
------------

[](#installation)

1. Run

    ```
    composer require mnabialek/laravel-authorize 1.2.*
    ```

    in console to install this module
2. Open `config/app.php` and:

- Comment line with

    ```
    Illuminate\Auth\AuthServiceProvider::class,
    ```
- Add

    ```
     Mnabialek\LaravelAuthorize\Providers\Auth::class,
     Mnabialek\LaravelAuthorize\Providers\Authorize::class,
    ```

    in same section (`providers`)

3. Run

    ```
    php artisan vendor:publish --provider="Mnabialek\LaravelAuthorize\Providers\Authorize"
    ```

    in your console to publish default configuration files, middleware, base policy class and unauthorized view
4. In `app/Http/Kernel.php` in `$routeMiddleware` add:

    ```
    'authorize' => \App\Http\Middleware\Authorize::class,
    ```

    to register `Authorize` middleware
5. Open `App\Http\Middleware\Authorize.php` and adjust `errorResponse` and `reportUnauthorizedAttempt` to your needs. In case defaults are fine to you, open `resources/views/errors/401.blade.php` and adjust this template to your needs - by default this view will be used if user has no permissions to given route.
6. Open your `User.php` model file and add

    ```
    use Mnabialek\LaravelAuthorize\Contracts\Roleable as RoleableContract;
    ```

    before class definition and make `User` class implement this interface, so it should look like this

    ```
    implements ..., RoleableContract
    ```

    As `...` you should leave all default interfaces this class `User` implements.
7. Make sure your `User` class implements `Roleable` Contract. In order to do that, you need to implement 2 methods: `hasRole` and `getRoles`. To simplify this, you can use default `Roleable` Trait. Just put inside your `User` class:

    ```
    use \Mnabialek\LaravelAuthorize\Traits\Roleable;
    ```

    Be aware this trait assumes you have `role` property for `User` model (what is equal that you have `role` column in your `users` table in database that hold your role name). In many cases it won't be true, so you need to override at least `getRoles` method to get valid user roles. Assuming you have one to many `role` relationship (user is only assigned to single role), custom implementation could look like this:

    ```
    public function getRoles()
    {
        return $this->role ? [$this->role->slug]: [];
    }
    ```

    Of course, if user can be assigned in your system to multiple roles or your database structure looks different, you should adjust this method code to match your application logic.

Getting started
---------------

[](#getting-started)

This module allows you to protect your routes with `authorize` middleware. You have 2 ways to use this middleware (you can use both in same application) - either based on `roles` or based on `permissions`.

Using this module you can set permissions both for authorized and not-authorized users to keep authorization layer consistent.

### 1. Role based authorization

[](#1-role-based-authorization)

You can specify middleware with arguments for example `authorize:manager,employee` - in this case only user role will be verified. In this example if user has any role `manager` or `employee` they will be allowed to access route, otherwise they won't be allowed to do that. However in above example also users with `super_roles` will be allowed to do this (`super_roles` in `config/authorize.php`). So if you define in `super_roles` also `admin`, also users with `admin` role will be allowed to access this route so you don't need to specify `admin` role in case you specify other roles (but of course you can do this if you want).

Nothing more needs to be configured to use this mode.

### 2. Permission based authorization

[](#2-permission-based-authorization)

**In this option, you cannot use closures in routes protected by `authorize` middleware. Make sure you don't use them in those routes or you'll get exception when applying `authorize` middleware**

If you use middleware without any arguments for example `authorize`, it will take advantage of [Laravel authorization](https://laravel.com/docs/5.2/authorization) with some extra changes to this mechanism. By default Laravel suggests creating policies for Models but it might be more reasonable in some cases to use policies for controllers and that's what this module does.

#### Configuration

[](#configuration)

Open `config/authorize.php` and in `super_roles` put roles name for which you allow everything so no extra checks will be made. In most cases it's reasonable to put here `admin` role but in some cases you might want to leave this empty if you want to run mode detailed rules. Put all roles you use in your application into `roles` section of `permissions` section.

#### Protecting your controllers

[](#protecting-your-controllers)

Let's assume we have controller `UserController` with default REST actions - `index`, `show`, `create`, `store`, `edit`, `update`, `destroy` and we would like to to protect this controller with `authorize` middleware because we don't want all users to allow all actions from this controller.

First, we need to open `app\Providers\AuthServiceProvider.php` and add policy mapping for our controller in `$policies` property:

```
\App\Http\Controllers\UserController::class => \App\Policies\UserControllerPolicy::class,
```

Now, let's create Policy class in `app/Policies/UserControllerPolicy.php` file with the following definition

```
