You get a bonus - 1 coin for daily activity. Now you have 1 coin

Authorization in Online Services. Policies and Gates in Laravel - Self-Check Test with Answers

Lecture Tests



Other peoples correct answered (level of difficulty) 50% questions

Brief theory of authorization in online services

Access Control is a comprehensive process that includes:

  • Identification — determining who is trying to log in (for example, entering a login).
  • Authentication — verifying the authenticity of an identity (for example, a password, biometrics).
  • Authorization — determining rights and permissions (for example, access to files or functions).

Authorization is the process that allows a user to gain access to certain resources or functions of a system after successful authentication. It includes checking access rights and determining which actions a user can perform. Authorization is the process that follows identification and authentication.​

Authorization in Online Services. Policies and Gates in Laravel - Self-Check Test with Answers

In Laravel, the authorization system is built around two key concepts — Policies and Gates.

  • Policies are classes that describe access rules for specific models. For example, you can define who can create, edit, or delete posts. Policies are convenient to use when you need to tie access rights to specific database objects.

  • Gates are global authorization checks defined as functions. They are suited for simple rules that are not tied to a specific model. For example, you can create a gate that checks whether a user is an administrator.

Laravel also provides convenient methods and directives:

  • Gate::allows(), Gate::denies() — for checking rights.
  • $this->authorize() — for invoking a policy in a controller.
  • Blade directives @can, @cannot, @canany — for checking rights in templates.
  • Policies are registered in AuthServiceProvider via the $policies property.

Thus, policies and gates allow flexible management of access to resources and actions in an application.

Authorization in Online Services. Policies and Gates in Laravel - Self-Check Test with Answers

Procedure for creating Policies and Gates in Laravel

In Laravel, a policy tied to models is used to authorize actions on specific Eloquent model instances. A policy is linked to a model and defines methods (view, update, delete, etc.) that are automatically checked through controllers, routes, and Blade.

Authorization in Online Services. Policies and Gates in Laravel - Self-Check Test with Answers

Authorization in Online Services. Policies and Gates in Laravel - Self-Check Test with Answers

order of checking

Authorization in Online Services. Policies and Gates in Laravel - Self-Check Test with Answers

In Laravel, Gate::before and Gate::after allow you to intercept the authorization process before and after the execution of specific rules. before is more often used for global rights (for example, an admin always has access), while after is used for logging or additional checks after the main decision.

  • Gate::before: executed before checking a specific rule. If it returns true or false, that result will be final and the rules will not be checked.

  • Gate::after: executed after checking a rule. It can be used for logging, auditing, or additional logic, but does not change the original decision (unless it explicitly returns true/false).

Example of using Gate::before and Gate::after

use Illuminate\Support\Facades\Gate;

Gate::before(function ($user, $ability) {
    // Admin always has access
    if ($user->isAdmin()) {
        return true;
    }
});

Gate::after(function ($user, $ability, $result) {
    // Log the authorization result
    \Log::info("User {$user->id} tried {$ability}: " . ($result ? 'granted' : 'denied'));
});

Explanation:

  • In before, it is checked whether the user is an admin. If so — access is granted without checking the remaining rules.

  • In after, the check result is recorded (for example, for auditing or statistics).

When to apply Gate::before and Gate::after in Laravel

  • before:

    • Global rights (for example, super-admin).

    • Universal exceptions (for example, users with a certain role).

  • after:

    • Logging and auditing actions.

    • Sending notifications about access attempts.

    • Additional checks that should not affect the main decision.

Comparison of Gate::before and Gate::after

Characteristic Gate::before Gate::after
Execution time Before checking rules After checking rules
Can change the result Yes Usually no (only if explicitly returned)
Typical tasks Global rights, super-admin Logging, auditing, notifications
Application Universal exceptions Analytics and monitoring
Practical application of Gate::before and Gate::after

In a real Laravel project:

  • before is convenient to use for admins or system users, so as not to write their rights into every policy.

  • after is useful for logging actions, especially in corporate systems, where it is important to track access attempts.

Sequence for creating and using policies and Gates in Laravel

Adding a role-usage flag

Creating a place to store roles in the database (in a one-to-many or many-to-many relationship)
or using an enum class
Creating a field (or pivot table) in the users table to bind to roles
then for each role there will be values that allow or deny certain actions

Creating a policy

php artisan make:policy PostPolicy --model=Post
  • The --model=Post flag immediately links the policy to the Post model.

  • The PostPolicy class will have the methods: view, create, update, delete, restore, forceDelete.

Registering the policy

In AuthServiceProvider:

protected $policies = [
    \App\Models\Post::class => \App\Policies\PostPolicy::class,
];

Laravel will automatically pick up the policy for the model.

Using it in controllers

Direct check:

public function update(Post $post)
{
    $this->authorize('update', $post);
    // update the post
}

Resource check:

public function __construct()
{
    $this->authorizeResource(Post::class, 'post');
}

Here 'post' — the name of the route parameter through which the model is extracted.

The authorize method

public function update(Post $post)
{
    $this->authorize('update', $post);
    // update logic
}

Checking the policy for a specific action.

The authorizeResource method In the controller's constructor you can bind resource methods to a policy:

public function __construct()
{
    $this->authorizeResource(Post::class, 'post');
}

Now the index, show, create, update, delete methods will be checked automatically.

Using it in routes

Route::delete('/posts/{post}', [PostController::class, 'destroy'])
    ->middleware('can:delete,post');

The can middleware checks the delete policy method for the Post model.

Via the can middleware

Route::get('/post/{post}/edit', [PostController::class, 'edit'])
    ->middleware('can:update,post');

Here the update policy is checked for the Post model.

For resource routes, you can combine this with authorizeResource in the controller, so as not to write middleware by hand.

Using it in views (Blade)

The @can directive

@can('update', $post)
    a href="{{ route('post.edit', $post) }}" Редактировать /a
@endcan

The @cannot directive

@cannot('delete', $post)
    p Удаление недоступно /p
@endcannot

The @canany directive

@canany(['update', 'delete'], $post)
    p Вы можете редактировать или удалять пост/p
@endcanany
@can('update', $post)
    a href="{{ route('posts.edit', $post) }}" Редактировать/a
@endcan

@cannot('delete', $post)
    p Удаление недоступно

Method correspondence table

Controller method Policy method Model parameter
index viewAny
show view Post $post
create create
store create
edit update Post $post
update update Post $post
destroy delete Post $post

Comparison of ways to plug authorization checks into various views and actions

Place of application Example When to use
Controller $this->authorize('update', $post) Logic inside the method
Controller (resource) $this->authorizeResource(Post::class, 'post') Automatic check for CRUD
Route ->middleware('can:update,post') Restricting access at the route level
View @can('update', $post) Displaying interface elements

Filtering data by owner and authorization

Using Gates and Policies in Laravel to filter data by owner is a correct and recommended approach, but it is important to understand their purpose: they are responsible for authorizing actions, not for the data selection itself. To filter Eloquent queries, it is better to combine policies with query scopes or middleware.

Gates and Policies: purpose
  • Gates — simple condition checks (for example, Gate::allows('update-post', $post)).
  • Policies — classes tied to models, where authorization methods are described (view, update, delete, etc.).
  • Main goal: allow or deny a user's action on a specific model.

Example with a Policy

// PostPolicy.php
public function view(User $user, Post $post)
{
    return $user->id === $post->user_id;
}

Application in a controller

public function index()
{
    $posts = Post::where('user_id', auth()->id())->get();
    return view('posts.index', compact('posts'));
}

Via a Scope without policies and gates

// In the Post model
public function scopeOwnedBy($query, $userId)
{
    return $query->where('user_id', $userId);
}

// Usage
$posts = Post::ownedBy(auth()->id())->get();
Theoretically, Gates or Policies can be used inside a Scope
 // PostPolicy.php
public function viewAny(User $user)
{
    return $user->role_id === RolesEnum::ADMIN->value;
}

// In the Post model
public function scopeOwnedBy($query)
{
    if (auth()->user()->can('viewAny', Post::class)) {
        return $query; // admin sees everything
    }

    return $query->where('user_id', auth()->id());
}

or

 // PostPolicy.php
public function viewNotOwner(User $user)
{
    // for example, a moderator can see other people's posts
    return $user->is_moderator;
}

// In the Post model
public function scopeVisibleFor($query)
{
    $user = auth()->user();

    if ($user->can('viewNotOwner', Post::class)) {
        // a moderator sees all posts except their own
        return $query->where('user_id', '!=', $user->id);
    }

    // a regular user sees only their own
    return $query->where('user_id', $user->id);
}

But if these are mixed together, the code becomes less transparent: the scope starts handling authorization tasks, even though its role is only filtering, and it is architecturally less clean.

Conclusions

Thus, in Laravel a policy tied to models is a centralized way to describe which users can perform actions on specific objects. It integrates at all levels: controllers, routes, and Blade.

In Laravel, policies can be used in several layers of the application — controllers, routes, and even views.

  • Filter data through scopes or the query builder.
  • Use Policies to check access to specific actions.
  • Combine both approaches: first filter the selection, then check authorization.
Best practices
Approach Pros Cons When to use
Policies Centralized authorization, easy to test Do not filter the data itself Checking access to a specific model
Scopes Clean code, reusability Need to remember to call it Filtering selections by owner
Middleware Universal, can restrict access to routes Less flexible for complex conditions Restricting access to entire resources

How to take the test

  1. Each question has 4 answer options.

  2. Only one option is correct — it is marked with an * symbol.

  3. After the list of answers there is a hint that briefly explains the correct choice.

  4. It is recommended to first try to answer on your own, and then check against the correct option and read the hint.

  5. The test can be taken sequentially or selectively — it covers various aspects of authorization in Laravel.

Self-check test on the topic of authorization in the Laravel framework

1. In what sequence is Access Control performed in online services:

  • a) 1. Authorization, 2. Authentication, 3. Identification
  • b) 1. Authentication, 2. Identification, 3. Authorization
  • c) 1. Identification, 2. Authentication, 3. Authorization *
  • d) 1. Identification, 2. Authorization, 3. Authentication

All three processes — identification, authentication, and authorization — are together usually referred to as access control. In IT, they are viewed as sequential stages of a single security mechanism during a user's interaction with a system.

2. How do you create a Policy in Laravel?

  • A) php artisan make:policy UserPolicy *
  • B) php artisan make:controller UserPolicy
  • C) php artisan make:middleware UserPolicy
  • D) php artisan make:model UserPolicy

The artisan make:policy command is used.

3. Where are Policies registered?

  • A) In routes/web.php
  • B) In AppServiceProvider
  • C) In AuthServiceProvider *
  • D) In Kernel.php

All policies are registered in AuthServiceProvider.

4. What is a Gate in Laravel?

  • A) A function for checking whether a user exists
  • B) A function for checking access rights *
  • C) Middleware for authentication
  • D) A logging service

Gate is a global authorization function.

5. How do you define a Gate?

  • A) Gate::define('edit-post', fn($user) => $user->isAdmin()); *
  • B) Route::get('edit-post', fn() => true);
  • C) Auth::check('edit-post');
  • D) Policy::create('edit-post');

A Gate is defined via Gate::define.

6. How do you invoke a Gate in code?

  • A) Gate::check('edit-post') *
  • B) Auth::gate('edit-post')
  • C) Route::gate('edit-post')
  • D) Policy::gate('edit-post')

The check is performed via Gate::check or Gate::allows.

7. What does the authorize() method do in a controller?

  • A) Checks rights via a Policy *
  • B) Runs middleware
  • C) Authorizes the user in the system
  • D) Creates a new record

authorize() invokes the corresponding policy.

8. Which Policy method checks access to a specific model?

  • A) view()
  • B) update() *
  • C) deleteAll()
  • D) createMany()

A Policy usually contains methods for each operation: view, update, delete.

9. What does the Gate::allows() method return?

  • A) true/false *
  • B) a Policy object
  • C) an array of rights
  • D) a string with the role

Gate::allows returns a boolean value.

Authorization in Online Services. Policies and Gates in Laravel - Self-Check Test with Answers

10. How do you tie a Policy to a model?

  • A) In AuthServiceProvider via the $policies property *
  • B) In routes/web.php
  • C) In Kernel.php
  • D) In config/app.php

The mapping between a model and its policy is specified in AuthServiceProvider.

11. What does the can() method on a user do?

  • A) Checks rights via Gate/Policy *
  • B) Checks the password
  • C) Creates a new role
  • D) Returns a list of routes

can() is a convenient method for checking authorization.

12. Which Blade directive is used to check rights?

  • A) @auth
  • B) @can *
  • C) @guest
  • D) @role

@can is used to check access rights in templates.

13. What does the deny() method do in a Policy?

  • A) Denies access and returns an error *
  • B) Deletes the model
  • C) Creates a new role
  • D) Logs the action

deny() returns a denial of access.

14. Which middleware is responsible for authorization?

  • A) auth
  • B) can *
  • C) throttle
  • D) guest

The can middleware checks access rights.

15. What is better to use for complex authorization logic?

  • A) Only middleware
  • B) Only Blade directives
  • C) Policy and Gate together *
  • D) Logs and events

For complex logic, a combination of Policy and Gate is used.

16. What does the Gate::denies() method do?

  • A) Returns true if access is allowed
  • B) Returns true if access is denied *
  • C) Creates a new policy
  • D) Checks the user's password

denies() is the opposite of allows(), returning true on denial.

Authorization in Online Services. Policies and Gates in Laravel - Self-Check Test with Answers

17. Which Policy method checks the deletion of a model?

  • A) remove()
  • B) delete() *
  • C) destroy()
  • D) erase()

The delete() method determines access to deletion.

18. How do you invoke a Policy check directly in a controller?

  • A) $this->authorize('update', $post); *
  • B) $this->auth('update', $post);
  • C) $this->policy('update', $post);
  • D) $this->gate('update', $post);

authorize() invokes the policy method for the model.

19. What does the before() method do in a Policy?

  • A) Checks all rights before the other methods *
  • B) Deletes the model
  • C) Creates a new role
  • D) Logs the action

before() allows you to globally allow or deny access.

20. Which method is used for mass viewing of models?

  • A) viewAny() *
  • B) viewAll()
  • C) list()
  • D) index()

viewAny() checks access to the list of models.

21. What does the Gate::forUser($user) method do?

  • A) Checks the rights of a specific user *
  • B) Creates a new role
  • C) Deletes a user
  • D) Returns a list of routes

forUser allows you to check the rights of another user.

Authorization in Online Services. Policies and Gates in Laravel - Self-Check Test with Answers

22. Which Blade directive checks for a denial of access?

  • A) @cannot *
  • B) @deny
  • C) @guest
  • D) @auth

@cannot is used to check for a denial.

23. What does the Gate::inspect() method do?

  • A) Returns an object with the check result and a message *
  • B) Returns only true/false
  • C) Creates a new policy
  • D) Deletes the model

inspect() gives a detailed check result.

24. Which Policy method checks the creation of a model?

  • A) add()
  • B) create() *
  • C) new()
  • D) insert()

create() is responsible for access to creation.

25. What does the Gate::authorize() method do?

  • A) Returns true/false
  • B) Throws an exception if access is denied *
  • C) Creates a new policy
  • D) Logs the action

authorize() throws an exception if access is denied.

Authorization in Online Services. Policies and Gates in Laravel - Self-Check Test with Answers

26. Which Policy method checks the update of a model?

  • A) edit()
  • B) update() *
  • C) change()
  • D) modify()

update() is responsible for access to modification.

27. What does the Gate::abilities() method do?

  • A) Returns a list of all defined rules *
  • B) Creates a new policy
  • C) Deletes the model
  • D) Checks the password

abilities() returns an array of all gates.

28. Which Policy method checks the viewing of a model?

  • A) show()
  • B) view() *
  • C) display()
  • D) read()

view() is responsible for access to viewing.

29. What does the Gate::any(['edit','delete']) method do?

  • A) Checks whether there is at least one permission *
  • B) Checks all permissions simultaneously
  • C) Creates a new policy
  • D) Deletes the model

any() returns true if at least one rule is satisfied.

Authorization in Online Services. Policies and Gates in Laravel - Self-Check Test with Answers

30. Which Policy method checks the restoration of a model?

  • A) restore() *
  • B) recover()
  • C) rollback()
  • D) return()

restore() is responsible for access to restoration.

31. Which Policy method checks the permanent deletion of a model?

  • A) forceDelete() *
  • B) delete()
  • C) destroy()
  • D) erase()

forceDelete() is used to check access to irrevocable deletion.

32. What does the Gate::none(['edit','delete']) method do?

  • A) Checks that not a single rule is satisfied *
  • B) Checks all rules simultaneously
  • C) Creates a new policy
  • D) Deletes the model

none() returns true if not a single rule is allowed.

Authorization in Online Services. Policies and Gates in Laravel - Self-Check Test with Answers

33. Which Policy method checks mass deletion of models?

  • A) deleteAny() *
  • B) removeAll()
  • C) destroyMany()
  • D) eraseAll()

deleteAny() is responsible for access to mass deletion.

34. What does the Gate::after() method do?

  • A) Executes after all checks and can change the result *
  • B) Creates a new policy
  • C) Deletes the model
  • D) Checks the password

after() allows you to globally change the check result.

35. Which Policy method checks mass creation of models?

  • A) createAny() *
  • B) addAll()
  • C) insertMany()
  • D) newAll()

createAny() is responsible for access to mass creation.

36. What does the Gate::before() method do?

  • A) Executes before all checks and can globally allow access *
  • B) Creates a new policy
  • C) Deletes the model
  • D) Checks the password

before() allows you to set a global rule ahead of the rest.

Authorization in Online Services. Policies and Gates in Laravel - Self-Check Test with Answers

37. Which Blade directive checks several rights at once?

  • A) @canany *
  • B) @canall
  • C) @authany
  • D) @roleany

@canany checks for the presence of at least one permission.

38. What does the Gate::check() method do?

  • A) Checks a rule and returns true/false *
  • B) Creates a new policy
  • C) Deletes the model
  • D) Logs the action

check() is used to check access.

Authorization in Online Services. Policies and Gates in Laravel - Self-Check Test with Answers

39. Which Policy method checks mass update of models?

  • A) updateAny() *
  • B) editAll()
  • C) changeMany()
  • D) modifyAll()

updateAny() is responsible for access to mass update.

40. What does the Gate::allows() method do?

  • A) Returns true if access is allowed *
  • B) Returns a Policy object
  • C) Creates a new role
  • D) Deletes the model

allows() returns true when access is granted.

41. Which Policy method checks mass restoration of models?

  • A) restoreAny() *
  • B) recoverAll()
  • C) rollbackMany()
  • D) returnAll()

restoreAny() is responsible for access to mass restoration.

42. What does the Gate::authorize() method do on denial?

  • A) Returns false
  • B) Throws an AuthorizationException *
  • C) Creates a new policy
  • D) Deletes the model

authorize() throws an exception when access is denied.

43. Which Policy method checks mass viewing of models?

  • A) viewAny() *
  • B) showAll()
  • C) displayMany()
  • D) readAll()

viewAny() is used to check access to the list of models.

44. What does the Gate::forUser() method do?

  • A) Checks the rights of the specified user *
  • B) Creates a new policy
  • C) Deletes a user
  • D) Returns a list of routes

forUser allows you to check the rights of another user.

Authorization in Online Services. Policies and Gates in Laravel - Self-Check Test with Answers

45. Which Policy method checks mass permanent deletion of models?

  • A) forceDeleteAny() *
  • B) destroyAll()
  • C) eraseMany()
  • D) removeAll()

forceDeleteAny() is responsible for access to mass permanent deletion.

46. Which Policy method checks mass editing of models?

  • A) editAny()
  • B) updateAny() *
  • C) changeAll()
  • D) modifyMany()

updateAny() is used to check access to mass editing.

47. What does the Gate::define() method do?

  • A) Defines a new authorization rule *
  • B) Creates a new policy
  • C) Deletes the model
  • D) Checks the password

define() is used to register a new gate.

48. Which Blade directive checks several rules at once?

  • A) @canany *
  • B) @canall
  • C) @authany
  • D) @roleany

@canany checks for the presence of at least one permission.

49. Which Policy method checks the deletion of a model?

  • A) remove()
  • B) delete() *
  • C) destroy()
  • D) erase()

delete() determines access to deletion.

50. What does the Gate::allows() method do on a successful check?

  • A) Returns true *
  • B) Returns false
  • C) Throws an exception
  • D) Creates a new policy

allows() returns true if access is granted.

51. Which Blade directive checks rights for a specific action?

  • A) @can *
  • B) @auth
  • C) @guest
  • D) @role

@can is used to check access rights in templates.

52. What is a Policy in Laravel?

  • A) A class for working with the database
  • B) A class for checking access rights *
  • C) Middleware for filtering requests
  • D) A controller for routes

A Policy is an object-oriented form of authorization that checks a user's rights.

53. Which HTTP status code is usually returned on an authentication error (for example, an invalid token or missing authorization)?

  • 200 OK
  • 401 Unauthorized *
  • 403 Forbidden
  • 404 Not Found

401 Unauthorized — the client failed authentication (invalid token, missing login).

Authorization in Online Services. Policies and Gates in Laravel - Self-Check Test with Answers

54. Which HTTP status code is usually returned on an authorization error (for example, access to a resource exists, but the rights are insufficient)?

  • 200 OK
  • 401 Unauthorized
  • 403 Forbidden *
  • 404 Not Found

403 Forbidden — the client is authenticated, but does not have the rights to perform the action.

Authorization in Online Services. Policies and Gates in Laravel - Self-Check Test with Answers

See also

  • [[b14136]]
  • [[b14135]]

Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "Running server side scripts using PHP as an example (LAMP)"

Terms: Running server side scripts using PHP as an example (LAMP)