Book Image

Laravel 5.x Cookbook

By : Terry Matula, Alfred Nutile
Book Image

Laravel 5.x Cookbook

By: Terry Matula, Alfred Nutile

Overview of this book

Laravel is a prominent member of a new generation of web frameworks. It is one of the most popular PHP frameworks and is also free and an open source. Laravel 5 is a substantial upgrade with a lot of new toys, at the same time retaining the features that made Laravel wildly successful. It comes with plenty of architectural as well as design-based changes. The book is a blend of numerous recipes that will give you all the necessary tips you need to build an application. It starts with basic installation and configuration tasks and will get you up-and-running in no time. You will learn to create and customize your PHP app and tweak and re-design your existing apps for better performance. You will learn to implement practical recipes to utilize Laravel’s modular structure, the latest method injection, route caching, and interfacing techniques to create responsive modern-day PHP apps that stand on their own against other apps. Efficient testing and deploying techniques will make you more confident with your Laravel skills as you move ahead with this book. Towards the end of the book, you will understand a number of add-ons and new features essential to finalize your application to make it ready for subscriptions. You will be empowered to get your application out to the world.
Table of Contents (17 chapters)
Laravel 5.x Cookbook
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

Using policies and guard to protect user pages


Here, I am going to show how we can use gate to keep users from deleting other people's Favorites.

Getting ready

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.

How to do it...

  1. Using Artisan, we will make a policy as follows:

    > php artisan make:policy FavoriteDeletePolicy
    
  2. It will create a file called app/Policies/FavoriteDeletePolicy.php.

  3. Then, we register it with the app/Providers/AuthServiceProvider.php class:

    Register Policy

  4. Now, we update the policy to have delete just as model:

  5. Then, we will plug the gate into the controller called app/Http/Controllers/FavoriteRemove.php:

  6. 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:

    Failed Response

  7. You will see that it works correctly if we put it back...