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

Self-testing tests with answers for policies and gates in Laravel

Lecture Tests



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

A brief theory on authorization in online services

Authorization is the process that allows a user to access specific resources or system functions after successful authentication. It involves checking access rights and determining what actions the user can perform.

Authorization is the process that follows authentication.

Self-testing tests with answers for policies and gates in Laravel

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 useful when you need to associate access rights with specific database objects.

  • Gates are global authorization checks defined as functions. They're suitable for simple rules that aren't tied to a specific model. For example, you could create a gate that checks whether a user is an administrator.

Laravel also provides convenience methods and directives:

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

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

Self-testing tests with answers for policies and gates in Laravel

How to create Policies and Gates in Laravel

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

Self-testing tests with answers for policies and gates in Laravel

Self-testing tests with answers for policies and gates in Laravel

verification procedure

Self-testing tests with answers for policies and gates in Laravel

Adding a Role Usage Flag

Create a storage location for database roles (in a 1-to-many or many-to-many relationship)
or using the enum class
Create a field (or table pivot) for the users table to link to roles
then for each role there will be values ​​of permission or prohibition for certain actions

Policy creation

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

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

Policy registration

In AuthServiceProvider:

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

Laravel will automatically pull the policy for the model.

Use in controllers

  • Direct check:

    public function update(Post $post)
    {
        $this->authorize('update', $post);
        // update post
    }
    
  • Resource check:

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

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

  • Authorize method

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

    Checking the policy for a specific action.

  • The authorizeResource method can be used to bind resource methods to a policy in the controller constructor:

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

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

Use in routes

Route::delete('/posts/{post}', [PostController::class, 'destroy'])
    ->middleware('can:delete,post');
  • Middleware can check the delete policy method for the Post model.

  • Through middleware can

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

    Here the update policy for the Post model is checked.

  • For resource routes, you can combine it with authorizeResource in the controller to avoid manually writing middleware.

Using in View (Blade)

  • @can directive

    @can('update', $post)
        a href="{{ route('post.edit', $post) }}" Edit /a
    @endcan
    
  • @cannot directive

    @cannot('delete', $post)
        p Deletion not available /p
    @endcannot
    
  • @canany's directive

    @canany(['update', 'delete'], $post)
        p You can edit or delete the post/p
    @endcanany
    
@can('update', $post)
    a href="{{ route('posts.edit', $post) }}" Edit/a
@endcan

@cannot('delete', $post)
    p Deletion is not available

Method Correspondence Table

Controller method Method of politics 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 methods for connecting authorization checks to various views and actions

Place of application Example When to use
Controller $this->authorize('update', $post) Logic inside a method
Controller (resource) $this->authorizeResource(Post::class, 'post') Automatic verification for CRUD
Route ->middleware('can:update,post') Route-level access restriction
Vyukha @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's important to understand their purpose: they authorize actions, not the actual data retrieval. For filtering Eloquent queries, it's best to combine policies with query scopes or middleware.

Gates and Policies: Purpose
  • Gates are simple conditional checks (e.g. Gate::allows('update-post', $post)).

  • Policies are classes associated with models that describe authorization methods (view, update, delete, etc.).

  • Main purpose: to allow or disallow user action on a specific model.

Example with Policy

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

Application in controller

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

Through Scope without policies and gates

// В модели Post
public function scopeOwnedBy($query, $userId)
{
    return $query->where('user_id', $userId);
}

// Использование
$posts = Post::ownedBy(auth()->id())->get();
Theoretically, you can use Gates or Policies in 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)) 
   {
   // the moderator sees all posts except his own
 return $query->where('user_id', '!=', $user->id);
 }  
// a regular user sees only his own 
return $query->where('user_id', $user->id);
 }

But if there is a mixture of them, the code becomes less transparent: the scope begins to solve authorization problems, although its role is only filtering and is architecturally less clean.

Conclusions

Thus, in Larave, model policies are a centralized way to describe which users can perform actions on specific objects. This is described on the website https://intellect.icu . They are integrated into all layers: controllers, routes, and blades.

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

  • Filter data using scopes or 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
Politics Centralized authorization, easy to test They don't filter the data themselves Checking access to a specific model
Scopes Clean code, reusability You have to remember the challenge Filtering selections by owner
Middleware Universal, you can restrict access to routes Less flexible for complex conditions Restricting access to entire resources

How to take the test

How to take the test

  1. Each question has 4 answer options.

  2. Only one answer is correct - it is marked with an *.

  3. After the list of answers, there is a hint briefly explaining the correct choice.

  4. It is recommended that you first try to answer the question yourself, then check the correct answer and read the hint.

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

1. What is a Policy in Laravel?

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

A Policy is an object-based form of authorization that checks user permissions.

2. How to 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 Gate in Laravel?

  • A) Filter for SQL queries
  • B) Function for checking access rights *
  • C) Authentication middleware
  • D) Logging service

Gate is a global authorization function.

5. How do I 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');

Gate is defined via Gate::define.

6. How do I call Gate in code?

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

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

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

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

authorize() calls the appropriate policy.

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

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

A policy typically contains methods for each operation: view, update, delete.

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

  • A) true/false *
  • B) Policy object
  • C) array of permissions
  • D) role string

Gate::allows returns a Boolean value.

Self-testing tests with answers for policies and gates in Laravel

10. How do I associate a Policy with a model?

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

In the AuthServiceProvider, specify the model and policy mapping.

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

  • A) Checks permissions 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 checks permissions?

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

@can is used to check access permissions in templates.

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

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

deny() returns access denied.

14. Which middleware is responsible for authorization?

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

Can middleware checks access rights.

15. What is best 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(); it returns true if denied.

17. Which Policy method is used to check for model deletion?

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

The delete() method determines access to deletion.

18. How can I call Policy validation 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() calls the policy method on the model.

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

  • A) Checks all permissions before 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 bulk viewing of models?

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

viewAny() checks access to a list of models.

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

  • A) Checks the permissions 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 permissions of another user.

22. Which Blade directive is used to check for access denial?

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

@cannot is used to check prohibition.

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

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

inspect() gives a detailed inspection result.

24. Which Policy method checks for model creation?

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

create() is responsible for creation access.

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.

Self-testing tests with answers for policies and gates in Laravel

26. Which Policy method checks for a model update?

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

update() is responsible for access change.

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 view of the model?

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

view() is responsible for accessing the view.

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

  • A) Checks if at least one permission * exists
  • B) Checks all permissions simultaneously
  • C) Creates a new policy
  • D) Deletes a model

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

Self-testing tests with answers for policies and gates in Laravel

30. Which Policy method checks for model recovery?

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

restore() is responsible for restoring access.

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

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

forceDelete() is used to check for permanent deletion access.

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

  • A) Checks that no rules are met *
  • B) Checks all rules at once
  • C) Creates a new policy
  • D) Deletes a model

none() returns true if no rule is allowed.

33. Which Policy method checks for 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 may change the result *
  • B) Creates a new policy
  • C) Deletes a model
  • D) Checks the password

after() allows Globally change the validation result.

35. Which Policy method validates the 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) Runs 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 before all other rules.

Self-testing tests with answers for policies and gates in Laravel

37. Which Blade directive checks multiple permissions 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 the rule and returns true/false *
  • B) Creates a new policy
  • C) Deletes the model
  • D) Logs the action

check() is used to check access.

39. Which Policy method checks for mass update of models?

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

updateAny() is responsible for access to mass updates.

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 a model

allows() returns true if access is allowed.

41. Which Policy method checks for bulk restore of models?

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

restoreAny() is responsible for access to bulk restore.

42. What does the Gate::authorize() method do if denied?

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

authorize() throws an exception if access is denied.

43. Which Policy method checks for bulk viewing of models?

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

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

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

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

forUser allows you to check the permissions of another user.

Self-testing tests with answers for policies and gates in Laravel

45. Which Policy method checks for mass hard deletion of models?

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

forceDeleteAny() is responsible for access to mass hard delete.

46. Which Policy method checks for mass editing of models?

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

updateAny() is used to check for 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 multiple rules at once?

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

@canany checks for at least one permission.

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

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

abilities() returns an array of all gates.

50. Which Policy method checks for mass hard deletion of models?

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

forceDeleteAny() is responsible for accessing mass hard deletion.

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

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

check() is used to check access.

Self-testing tests with answers for policies and gates in Laravel

52. Which Policy method checks for mass model restore?

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

restoreAny() is responsible for access to mass restore.

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

  • A) Return 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(); it returns true if denied.

54. Which Policy method checks for mass model creation?

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

createAny() is responsible for access to mass creation.

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

  • A) Checks that no rules are satisfied *
  • B) Checks all rules at once
  • C) Creates a new policy
  • D) Deletes the model

none() returns true if no rules are allowed.

Self-testing tests with answers for policies and gates in Laravel

56. Which Policy method checks whether a model is viewable?

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

view() is responsible for access to the view.

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

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

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

58. Which Policy method checks for model deletion?

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

delete() determines deletion access.

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

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

inspect() returns a detailed inspection result.

60. Which Policy method checks for a model update?

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

update() is responsible for access to edits.

61. What does the Gate::allows() method do if the check is successful?

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

allows() returns true if access is allowed.

62. Which Policy method checks for bulk editing of records?

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

updateAny() is used to check for bulk editing.

63. What does the Gate::authorize() method do if it is denied?

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

authorize() throws an exception if access is denied.

64. Which Blade directive checks permissions for a specific action?

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

@can is used to check access rights in templates.

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

  • A) Runs before all other 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 before all other rules.

66. Which Policy method checks for bulk deletion of records?

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

deleteAny() is responsible for accessing bulk deletions.

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

  • A) Runs 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 result of the check.

68. Which Policy method checks for model recovery?

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

restore() is responsible for access to recovery.

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

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

forUser allows you to check the permissions of another user.

Self-testing tests with answers for policies and gates in Laravel

70. Which Policy method checks for permanent deletion of a model?

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

forceDelete() is used to check for access to permanent deletion.


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

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

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