Here, I am going to show how we can use gate to keep users from deleting other people's Favorites.
A fresh install of Laravel will do. But if you have followed along this far, you will have all the routes and controllers in place.
Using Artisan, we will make a policy as follows:
> php artisan make:policy FavoriteDeletePolicy
It will create a file called
app/Policies/FavoriteDeletePolicy.php
.Then, we register it with the
app/Providers/AuthServiceProvider.php
class:Now, we update the policy to have
delete
just asmodel
:Then, we will plug the gate into the controller called
app/Http/Controllers/FavoriteRemove.php
:Once this is done, you will see how users are rejected if they do not own Favorite; for a moment, I will update the policy to be this—the opposite of what we really want—just for example:
This is the response that they will get: