Laravel 5: Resolving Authentication Policies With policy

April 14, 2018 —John Koster

The policy helper function can be used to retrieve a policy (a policy class can be any valid PHP class) instance for a given $class. The $class can be either a string or an object instance. If no policies for the given $class have been registered with the application an instance of InvalidArgumentException will be thrown.

The policy helper functions internally makes a call to the getPolicyFor method on the authentication gate instance.

#Signature

The signature of the policy function is:

1function policy(
2 $class
3);

#Example Use

Assuming we had the following classes available to us:

1<?php
2 
3namespace App;
4 
5use Illuminate\Database\Eloquent\Model;
6 
7class Account extends Model
8{
9 //
10}

In app/Policies/AccountsPolicy.php:

1<?php
2 
3namespace App\Policies;
4 
5use App\User;
6use Illuminate\Auth\Access\HandlesAuthorization;
7 
8class AccountsPolicy
9{
10 use HandlesAuthorization;
11 
12 public function create(User $user)
13 {
14 if ($user->isAdmin()) {
15 return true;
16 }
17 }
18 
19}

Note: All custom policies need to be mapped to their associated model class; this is typically done within the app/Providers/AuthServiceProvider.php file. Remember: policies can be applied to any data model or object in an application; not just Eloquent ORM models.

In app/Providers/AuthServiceProvider.php

1<?php
2 
3namespace App\Providers;
4 
5use App\Account;
6use App\Policies\AccountsPolicy;
7use Illuminate\Support\Facades\Gate;
8use Illuminate\Foundation\Support\Providers
9 \AuthServiceProvider as ServiceProvider;
10 
11class AuthServiceProvider extends ServiceProvider
12{
13 /**
14 * The policy mappings for the application.
15 *
16 * @var array
17 */
18 protected $policies = [
19 Account::class => AccountsPolicy::class
20 ];
21 
22 /**
23 * Register any authentication/authorization services.
24 *
25 * @return void
26 */
27 public function boot()
28 {
29 $this->registerPolicies();
30 
31 //
32 }
33}

With the previous files available to use, we could resolve the associated policy for the "App\Account" class with the following call to the policy helper function:

1// Resolve an instance of the AccountsPolicy class.
2$policy = policy(App\Account::class);

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.