Laravel how to make authorization

Learn how to build an authentication system with Laravel, step-by-step, with an example app.

Laravel Authorization

Laravel provides a simple way to authorize user actions against a given resource. It provides a nice interface for organizing authorization logic using "gates" and "policies". The gates and policies determine whether a user is authorized to access a certain resource.

Let's say we have a blog app and want to authorize users who can create, edit, and delete posts. We can create a policy for the Post model to handle this authorization logic.

// app/Policies/PostPolicy.php

namespace AppPolicies;

use AppPost;
use AppUser;

class PostPolicy
{
    public function create(User $user)
    {
        return $user->isAdmin();
    }

    public function update(User $user, Post $post)
    {
        return $user->id === $post->user_id || $user->isAdmin();
    }

    public function delete(User $user, Post $post)
    {
        return $user->id === $post->user_id || $user->isAdmin();
    }
}

We can register the policy in the AuthServiceProvider:

// app/Providers/AuthServiceProvider.php

public function boot()
{
    $this->registerPolicies();

    // ...

    Gate::define('posts.create', 'AppPoliciesPostPolicy@create');
    Gate::define('posts.update', 'AppPoliciesPostPolicy@update');
    Gate::define('posts.delete', 'AppPoliciesPostPolicy@delete');
}

Now we can use the gates to authorize the user actions:


// app/Http/Controllers/PostController.php

public function store(Request $request)
{
    $this->authorize('posts.create');

    // Create the post...
}

public function update(Post $post, Request $request)
{
    $this->authorize('posts.update', $post);

    // Update the post...
}

public function delete(Post $post)
{
    $this->authorize('posts.delete', $post);

    // Delete the post...
}

In this example, we used the gates to authorize the user actions. However, Laravel also provides the ability to use "policies" for authorization. Policies allow us to group related authorization logic into a single class. Policies can also be used to provide more granular control over user authorization.

To use a policy, we first need to register it in the AuthServiceProvider:

// app/Providers/AuthServiceProvider.php

public function boot()
{
    $this->registerPolicies();

    // ...

    Gate::policy('AppPost', 'AppPoliciesPostPolicy');
}

Now we can use the policy to authorize the user actions:


// app/Http/Controllers/PostController.php

public function store(Request $request)
{
    $this->authorize('create', Post::class);

    // Create the post...
}

public function update(Post $post, Request $request)
{
    $this->authorize('update', $post);

    // Update the post...
}

public function delete(Post $post)
{
    $this->authorize('delete', $post);

    // Delete the post...
}

Using policies, we can easily organize our authorization logic and make sure our user actions are authorized correctly.

Answers (0)