Skip to content

Commit 34a9e09

Browse files
authored
Gating with custom message (#90)
1 parent c190b3f commit 34a9e09

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

content/4.digging-deeper/3.gates.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,3 +38,44 @@ class UserResource extends Resource
3838
// ...
3939
}
4040
```
41+
42+
## Policy messages in gates
43+
44+
To surface policy messages explaining authorization failures, first set the config `rest.gates.message.enabled` to `true`.
45+
Enabling this changes the `gates` payload shape returned by the `search` endpoint and may require frontend updates.
46+
47+
In your policy, return an authorization `Response`:
48+
49+
```php
50+
use App\Models\Post;
51+
use App\Models\User;
52+
use Illuminate\Auth\Access\Response;
53+
54+
/**
55+
* Determine if the given post can be updated by the user.
56+
*/
57+
public function update(User $user, Post $post): Response
58+
{
59+
return $user->id === $post->user_id
60+
? Response::allow()
61+
: Response::deny('You do not own this post.');
62+
}
63+
```
64+
65+
This changes the `search` gates payload by adding a `message` and `allowed` keys:
66+
67+
```json
68+
{
69+
"data": [
70+
{
71+
"id": 1,
72+
"gates": {
73+
"authorized_to_update": {
74+
"allowed": false,
75+
"message": "You do not own this post."
76+
}
77+
}
78+
}
79+
]
80+
}
81+
```

0 commit comments

Comments
 (0)