How to do authorization in laravel 5.2?

Its very simple and can be done very easily.
In this tutorial we will look into followings:
How to define Abilities?
How to check Abilities?

  • Via The Gate Facade
  • Via The User Model
  • Within Blade Templates
  • Within Form Requests


What are policies?

How to check abilities/policies in Controller?

Before going to start tutorial just create Place Controller and Place model

php artisan make:controller PlaceController
php artisan make:model Place

How to define Abilities?
Ability means what user can do, operations permitted by user.
You can define abilities in your AuthServiceProvider boot method as below:

<?php 
namespace App\Providers; 
use Illuminate\Contracts\Auth\Access\Gate as GateContract; 
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; 
class AuthServiceProvider extends ServiceProvider { 
/*
* * Register any application authentication / authorization services. 
* * @param \Illuminate\Contracts\Auth\Access\Gate $gate 
* @return void 
*/ 
public function boot(GateContract $gate) { 
$this->registerPolicies($gate);

        $gate->define('update-place', function ($user, $place) {
            return $user->email==='jaffar@xys.xyz';//just for time being and you can insert your own logic here
        });
    }
}

and also ability can be defined via class method:

<?php 
namespace App\Providers; 
use Illuminate\Contracts\Auth\Access\Gate as GateContract; 
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; 
class AuthServiceProvider extends ServiceProvider { 
/*
* * Register any application authentication / authorization services. 
* * @param \Illuminate\Contracts\Auth\Access\Gate $gate 
* @return void 
*/ 
public function boot(GateContract $gate) { 
$this->registerPolicies($gate);

        $gate->define('update-place', 'Class@method');
    }
}

How to check Abilities?

Abilites can be check by following mehtods:
via gate facade

	 $place = Place::findOrFail($id);

        if (Gate::denies('update-place', $place)) {
            abort(403);
        }

via user model

	 $place = Place::findOrFail($id);
if ($request->user()->cannot('update-place', $place)) {
            abort(403);
        }

        // Update Place...

via blade directives

@can('update-place', $place)
    <a href="/place/{{ $place->id }}/edit">Edit place</a>
@endcan

Withing form request


public function authorize()
{
    $placeId = $this->route('place');

    return Gate::allows('update-place', Place::findOrFail($placeId));
}

What are policies?
Defining all of your authorization logic in the AuthServiceProvider is not good and
also will be dificult to scale and maintain code.
For this reason laravel provides out of box solution for this
lets create policy PlacePolicy

php artisan make:policy PlacePolicy

after running above command go to file Policies/PlacePolicy.php
and put following contents;

<?php 
namespace App\Policies; 
use Illuminate\Auth\Access\HandlesAuthorization; 
class PlacePolicy { use HandlesAuthorization; 
/*
* * Create a new policy instance. 
* * @return void 
*/ 
public function __construct() { 
   // 
} 
/*
* * Determine if the given place can be updated by the user. 
* * @param \App\User $user * @param \App\Models\Place $place 
* @return bool 
*/ 
public function update(\App\User $user, \App\Models\Place $place) { 
return $user->email === 'jaffar@xyz.xyx;
    }
}

now register your policies in AuthServiceProvider
and AuthServiceProvider should look like below:

<?php 
namespace App\Providers; 
use Illuminate\Contracts\Auth\Access\Gate as GateContract; 
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; 
class AuthServiceProvider extends ServiceProvider { 
/*
* * The policy mappings for the application. 
* * @var array 
*/ 
protected $policies = [ 'App\Place' => 'App\Policies\PlacePolicy',];

    /**
     * Register any application authentication / authorization services.
     *
     * @param  \Illuminate\Contracts\Auth\Access\Gate  $gate
     * @return void
     */
    public function boot(GateContract $gate)
    {
        $this->registerPolicies($gate);

        //
    }
}

How to check abilities/policies in Controller?

To check this just create a rout in your routes.php file for updating place

Route::get('/places/update/{id}', 'PlaceController@update');

and update you PlaceController@update method as below:

public function update($id){
    	
    	//$place = factory(\App\Place::class)->make();
    	$place = Place::find($id);
    	$this->authorize('update', $place);
    	return ['updated'=>1];
    }

You can find complete demo project on github

Reference:
https://laravel.com/docs/5.2/authorization

About Jaffar Hussain

Jaffar Hussain is an Enthusiastic Software Engineer having vast experience in Zend, SugarCRM, Laravel php frameworks and good command on databases Mysql, MongoDB, SqlServer 2008.

  • Milos

    Awesome! Keep on writing nice articles on 5.2 :))

  • fix your messed up code formatting, it’s unreadable