Skip to content

Commit b6e5b7f

Browse files
tdwestenlindyhopchris
authored andcommitted
Add docs for custom error messages
1 parent 1083796 commit b6e5b7f

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Diff for: docs/4.x/requests/authorization.md

+44
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,50 @@ will not be allowed to perform that action. So, if you have defined a policy,
7272
don't forget to define all of its relevant authorization methods.
7373
:::
7474

75+
### Custom error messages
76+
77+
If you want to return a custom error message when a user is not authorized
78+
or based on the result of the authorization, you can use the
79+
`Illuminate\Auth\Access\Response` class. This class allows you to return a
80+
custom response when the user is not authorized or when the authorization
81+
fails.
82+
83+
For example, if you want to return a custom error message when a user is not
84+
authorized to update a post, you can use the `deny` method:
85+
86+
```php
87+
namespace App\Policies;
88+
89+
use App\Models\Post;
90+
use App\Models\User;
91+
use Illuminate\Auth\Access\Response;
92+
93+
class PostPolicy
94+
{
95+
96+
/**
97+
* Authorize a user to update a post.
98+
*
99+
* @param User $user
100+
* @param Post $post
101+
* @return Response
102+
*/
103+
public function update(User $user, Post $post): Response
104+
{
105+
if ($user->is($post->author)) {
106+
return Response::allow();
107+
}
108+
109+
return Response::deny(
110+
'You are not the author of this post. You cannot update it.'
111+
);
112+
}
113+
}
114+
```
115+
116+
This will return a `403 Forbidden` response with the custom error message
117+
when the user is not authorized to update the post.
118+
75119
### Relationship Authorization
76120

77121
Laravel JSON:API also expects policy methods to be defined for each relationship

0 commit comments

Comments
 (0)