Laravel 5.8 – From The Ground Up - Laravel 5.8 Tutorial From Scratch – e44 – Policies

Education, Programming

Laravel 5.8 – From The Ground Up

52 Lessons

Laravel 5.8 Tutorial From Scratch – e44 – Policies

welcome back in this episode we're gonna be tackling policies now policies is a very convenient way for us to authorize certain users to be able to do certain

actions in our application the easy example of this would be that you may have two different types of users for your app you may have admin users and you may have just regular users of

course administrators of your app can do certain things that regular users just can't do so what is the easiest way to handle this in laravel the easiest way is through the use of policies now the

first thing to understand about policies is that policies attached to models so they are protecting a specific model they are for protecting resources of your application and what I mean by that

is that they are attached to some sort of table in your database I think it will become a little bit more clear once we start to talk about what I want to do for our project let me jump into chrome

and what I have set up here is I have this new user called admin user and then I have the same exact app pulled up as test user so we will be testing against these two users obviously giving

administrative rights to this Left screen and just a regular user here on the right and I want to show you the difference between that so I am logged in as a user here and right now these

two users can perform the exact same actions now if I go to my customers list of course I have this new add customers but perhaps I only want to be able to add new customers if I'm an

administrator if I'm just a regular user I don't want people to be able to add customers to my list so I'm gonna say that that is an admin only type of thing so let's get right to it so we can get

that done let's jump to the terminal and run PHP artisan as we've always done let's go back up here to the make and we have this make policy so let's check out what we could do with that PHP artisan

help make policy so we see that a name is required and we do have certain parameters now the options that I want to use in this case will be model like I said policies are

attached to models so what model is this well of course this is our customer model all right so let's make that command now PHP artisan make policy and what's the policy gonna be called it's

gonna be called customer policy and we need a model like I said models need to be attached to policies so we'll run the – M flag and what is the model name customer that is the model we are

looking for so there we go policy created jump back to phpstorm and let's go into apps and now you have this new policies directory and inside there we have this customer policy so this

class is pretty much ready to go and what it has is each of the restful methods that we've been working towards since the restful controllers lesson if you didn't check out those I did a four

part series on restful controllers a little bit earlier in this series definitely check that out because it will make this a lot easier to understand so with that being said we

have it creates we have an update and delete and a restore and a force delete so everything here has been mocked out for us so let's start right away so the one that I want to do is that create

method remember I said that I didn't want my customers to be able to add new customers unless they were an administrator so we need to get rid of this button on this side and we need to

give it to this son so let's write the policy now so to create a method it gives us a user class and you'll see that across the board you see that each of these methods you get a

user and if applicable you do get the customer in our case so you get the model and you get the user and now out of each of these functions you have to return true or false basically saying is

the user that I gave you authorized to perform whatever this is on this customer and if they are then of course it will proceed if they don't then of course they get an error all right so

let's say the create method how can we prove that a user can create a customer so let's say this let's return in or and what are we looking for we're looking for the users email and let's

just pass it in an array of different emails so in my case let me jump the table Plus to show you what I have I have this test user and then I have this admin at admin comm of course you could

always add a new column here and maybe call it administrator or admin and in that case you could just check that column I'm gonna do it by limiting what emails I am authorizing to perform so

admin and admin comm will be authorized to create that so I'm gonna add that right here to this array and if you had another one of course you can make a new line and add as many as you want here

again this is just one way of doing it you could do it in many different ways but I do find that this works for administrative purposes because typically you only have one or two of

these super users so we are good to go that admin will be the only one authorized to create a new record so how do we actually apply this well to apply this lets go to the customer controller

and then go to my store method and before we actually run the store operation we need to let our controller know that we need to authorize this request and we use that same keyboard

will say this authorized so we're going to authorize a create and then we need to give it the model that we're gonna create so what are we going to create we're gonna create a customer class

there we go all right so we should be good to go let's give this a shot and see what happens right here on the right side remember I am logged in as a non admin let me go ahead and add a new

customer now and see what happens add customer nope can't do it 403 you are not authorized let's do the same exact thing over here on the Left where we are logged in as an admin any

information we'll do add customer BAM we did it so we are successfully limiting someone from being able to do it unless they're an administrator great however it wouldn't really make any sense to

have this add new customer button if our users are not authorized to perform that action so we are protecting our back-end meaning that they're not able to do it even if they went through the terminal

and curl'd directly into our application they would not be able to submit that request so we are protected however showing this form really makes no sense so how do we remove this add

new customer conditionally that's actually quite simple as well once you have your policy in place let's jump back to phpstorm and let's go to the index so index stop blade that PHP file

and let's find that button and see right here add new customer alright so let me wrap all of this in a new directive that we haven't touched on before and it is can so can the user perform this and can

and then inside of here we'll paste that back in so what do we pass to can we pass something very similar to what we had before so we are authorizing a create and it needs an app customer

class remember this create method is kind of special because there actually isn't a model yet for it so in that case we're only gonna pass in the model class itself so with that

being said head back to Chrome and now let's refresh this page and we see that that button is gone and this one nope still there it looks like we accidentally grabbed the customers list

as well so let's fix that in just a second here yep there it is so let's pull this out and let's create outside of here some more HTML will say give me a row with column 12 and inside of that

then we'll have our customers list so that should fix it hit refresh here hit refresh here so there we are so we are no longer showing that add new customer at all as you see there nope you can't

see it that's pretty cool so that's how policies work let's do another one what if we wanted to only allow deletes okay so let's work on that one now back to my policy let's find the delete method and

there it is so how do we authorize this we could use the exact same logic that we have here before I'm going to copy this and in my delete I will paste that logic in so only people that have that

are able to delete now for the sake of this example just to prove how it will work I'm gonna go ahead and change this to maybe bananas and obviously that user

doesn't exist I just want to show you how we will fail even for the admin now so let's go back to our controller and go to the destroy method and we also need to authorize this request so let's

say this authorize a delete request and as a second parameter we don't pass it in the class but we actually pass in the customer model we definitely want to pass that in all right let's go back to

Chrome and I'm gonna try to delete one of these records remember this is our administrator here and I will try to hit the leap and nope it does not let me do that okay so now let's change that email

again so that it is the correct one admin at admin comm hit save go back hit delete and this time we are able to do it so that's pretty cool and that's how that works

so a couple of things about policies remember that some of the methods have two parameters and some of them have only one so what are the ones that have one well the creates and that makes

sense because there is no model yet but you're creating the model so of course you could not have a model if you haven't created it yet so for that you only need a user so when you use that

method and let's jump up here to the store method what you pass it in as a second argument because you always do need a second argument in the authorized is you pass in the model class right

what we're passing into it is the full model class not a particular model in our application does that make sense notice that here there is no customer however when we did it in the destroy

method we are receiving a customer right so that's what we're gonna pass in instead so you authorize the request so that's one thing about policies remember that some have one and some have two so

what other ways can we authorize a request of course as in many things with label this is not the only way that you can authorize a request another common one that you can do is through a

middleware a custom middleware and those are pretty cool let's say that for some reason I don't want to show customers information unless your administrator meaning this view right here I don't

want anybody unless you're an administrator to see the details of a particular customer of course this is our show view so we want to protect our show view and I'm gonna

do it in a different way just to show you how to do it so let's jump back to phpstorm and let's go to view so view of course is pertaining to show and I will go ahead and bring the exact same code

that I have here so that way only the admin at admin comm can actually view the records okay so now let's jump to the web dot PHP file and let's find that show I did jump into a resource for

controller I will actually disable this for now and I will bring back all of this code here remember this code this single line here and this is the exact same thing but for

demonstration purposes I only want to do it to one route of course it is possible to put policies in an entire resource but for this demonstration the show view is the one that I want to protect and

here it is so when we call customers slash an ID I am hitting my customers controller at the show method all right let's that now and we'll say middleware and inside middleware will

have a string and we'll say it can : so it can view and then what is the model that we are using we're using the customer model so we'll just use customer and this is the customer that I

want to grab right here so let's do that now customer safe alright that's it let's go back to the browser I'm gonna hit refresh on this side and now we are forbidden but if we hit refresh as an

administrator it looks like there's a name route here that we are not calling and that's the customers dot edit all right let me do that really quick let's see let's add name customer dot edit

let's see now refresh looks like customer does destroy also need the name remember in the previous lesson we actually refactor this to use named routes so now when we

switched out of our resource controller we no longer have those named routes let's just name all of them create store and finally update and there we are alright so that was just a little mishap

from when we switched over from resource you see how that works so admins are allowed to view details regular customers are not so there we are if I click on one I am no longer allowed to

do that then of course we can also restrict this so that you cannot click on a link because it wouldn't make sense for you to be able to click on a link if larvae already knows that you are not

authorized to view that resource so I'll leave that as a homework assignment I want you to be able to control the link and let me show you where that would be if we go back to our index method right

here this is the anchor tag that I'm talking about I only want to show this anchor tag if the customer is authorized to be able to view that resource otherwise they should not be able to do

that so with that being said go ahead and pause the video and then I'll show you the solution so now let's go ahead and handle that case so all you have to do is actually just break this up into a

new line and we can do this in one of two ways right so we can either wrap this line and this line together or we could just repeat it it's up to you I'm gonna repeat it because I think it'll

look cleaner so let's bring the same exact directive in here and let's say can so if it can view the customer so if it can view the customer go ahead and give them the link and we'll just say

and can and can down here and that's it so if it can view it then go ahead and show them that but what about the inverse of that what about cannot that's the other one

we haven't learned that one so if it cannot view the customer in that case we're just simply going to grab the customers name and display that instead so and cannot and will reinvent that and

there we go if we go back we'll hit refresh and no links at all as you can tell but of course in the admin page we do have links so this is clickable and this is not so that's it that's the

overview of policies and level as another side project go ahead and try to implement the entire customer policy so that way you have a very nice customer policy running right alongside one last

note to talk about policy is that policies are Auto discoverable notice that we did not actually register a policy but this is a relatively newer feature of Larry

Moe if you ever needed to register a policy then you need to go into your auth service provider and right here under policies you need to put in your policy so in this case we would say

model is customer so app customer belongs to the customer policy and that's it that's all you will have to do to manually register a policy so that's it for this episode go ahead and review

the documentation on policy and see if you can find any other tips and tricks on how to use policies this is a very common thing for a lot of applications so definitely familiarize yourself with

policies and when you're ready let's move on to the next topic

Laravel policy files allow us to limit any of the CRUD actions in our app allowing us to stop unwanted behavior. Follow along as we work out a policy for our Customer’s model.

For the best experience, follow along in our interactive school at

Laravel Policy

DigitalOcean Referral

Course Source Code

Hit us up on Twitter with any questions or comments @codertape (

About This Course

Ready to get started on your path to Laravel Artisan? In this series, we are breaking down all of the basics of Laravel to get you comfortable using the world’s most popular PHP framework. Let’s get started!

    add to database laravel admin laravel artisan Artisan Command artisan commend create artisan console artisan laravel command authentication in laravel belongsto belongsto laravel example coding tutorials create artisan command create command artisan create new command artisan Create your own crud laravel crud laravel tutorial crud resource laravel crud with file upload custom artisan commands custom artisan commands laravel custom laravel database configuration laravel database relationship digital ocean dotenv eager loading eager loading in laravel eager loading vs lazy loading laravel eloquent eloquent accessors eloquent mutators eloquent orm feature testing laravel fetching data in laravel filesystem laravel form requests full stack vue gate and policy laravel google optimize hasmany hasmany laravel hasmany laravel example hasmany relationship in laravel hasone hasone relationship in laravel How to create how to queue email how to use queue installing laravel intervention image laravel laravel 5 laravel 5 auth laravel 5.4 queue laravel 5.5 queue laravel 5.8 laravel 5.8 artisan command laravel 5.8 artisan console laravel 5.8 auth tutorial laravel 5.8 authentication laravel 5.8 commands laravel 5.8 crud laravel 5.8 crud example laravel 5.8 custom middleware laravel 5.8 deprecations laravel 5.8 eager loading laravel 5.8 elixir laravel 5.8 event listeners laravel 5.8 events laravel 5.8 feature laravel 5.8 features laravel 5.8 global middleware laravel 5.8 install laravel 5.8 lazy loading laravel 5.8 listeners laravel 5.8 middleware laravel 5.8 multi auth laravel 5.8 named resource routes laravel 5.8 named routes laravel 5.8 new feature laravel 5.8 own artisan command laravel 5.8 queue laravel 5.8 queues laravel 5.8 routing laravel 5.8 telescope laravel 5.8 tutorial laravel 5.8 user auth laravel 5.8 user authentication laravel 5.8 what's new laravel 5.9 laravel admin permissions laravel api laravel artisan command laravel artisan console laravel assets laravel auth laravel auth role laravel authentication laravel authorization laravel axios post example laravel background process laravel background task laravel background worker laravel beginner to master laravel belongsto laravel belongsto vs hasone laravel belongstomany laravel best packages laravel best practices laravel best tutorial laravel bootstrap laravel command laravel command line laravel commands tutorial laravel composer install laravel connect db laravel console command laravel console testing laravel contact form send email laravel controllers laravel create laravel crud laravel crud policy laravel custom command laravel custom middleware laravel database laravel database configuration laravel database relationships laravel database seeder laravel database settings laravel db seed laravel db settings laravel debugging laravel deploy aws laravel deploy digital ocean laravel deploy on digitalocean laravel deploy on server laravel deploy to production laravel deployment laravel digitalocean laravel drag and drop file upload laravel dropzone file upload laravel dropzone image upload laravel e-commerce laravel eager loading laravel eager loading tutorial laravel eager loading with condition laravel elixir laravel eloquent laravel eloquent belongsto laravel eloquent crud laravel eloquent hasmany laravel eloquent where laravel eloquest tutorial laravel events and queue laravel events tutorial laravel factory laravel feature test laravel feature testing laravel fetching data from database laravel file storage laravel fillable example laravel flash message notification laravel for beginners laravel form validation laravel forms laravel forms bootstrap snippets laravel from scratch laravel from the ground up laravel front end laravel frontend tutorial laravel gate and policy tutorial laravel global middleware laravel hasmany laravel hasone laravel i18n laravel installation laravel installation mac laravel intervention image tutorial laravel javascript tutorial laravel jobs queue laravel language laravel language switcher laravel language tutorial laravel languages laravel lazy loading laravel listener event laravel listeners laravel localization laravel login laravel mailable tutorial laravel many to many relationship example laravel markdown email laravel markdown mail laravel mass assignment laravel middleware laravel migrate fresh laravel mix laravel mix 5.8 laravel mix vue laravel model factory tutorial laravel multiple language laravel mysql json laravel named resource routes laravel named routes laravel new features laravel news laravel nginx laravel node modules laravel npm install laravel npm run watch error laravel one to one laravel paginate laravel paginate link laravel pagination laravel pagination 5.8 laravel pagination links laravel pagination tutorial laravel phpunit laravel phpunit testing laravel pivot table example laravel policy laravel preview laravel query optimization laravel queue laravel queue event listener laravel react laravel register user laravel registration laravel registration validation laravel relationships laravel reset password laravel role middleware laravel role permission laravel roles laravel route group middleware laravel routes laravel routing laravel routing with parameters laravel sass laravel save file to database laravel scopes laravel seo tutorial laravel server laravel session data laravel ssl laravel supervisor laravel tailwind css laravel tailwind setup laravel tdd laravel tdd tutorial laravel telescope laravel telescope installation laravel telescope tutorial laravel test driven development laravel test workflow laravel testing laravel testing controllers laravel testing tutorial laravel tools laravel translation laravel tutorial laravel tutorial for beginners laravel ubuntu server laravel ubuntu tutorial laravel unit testing controllers laravel upload file laravel upload image to storage laravel upload multiple files at once laravel upload multiple image to database laravel upload multiple images laravel url slug laravel vue laravel vue js crud laravel vue setup laravel vue tutorial laravel vue.js laravel webpack error laravel webpack tutorial lazy loading lazy loading laravel lazy loading vs eager loading learn laravel learn laravel framework step by step localization in laravel localization laravel many to many laravel mvc tutorial for beginners in php mvc tutorial laravel mysql mysql relational database mysql relationship n + 1 problem n + 1 problem laravel new artisan command npm install npm run dev npm run watch laravel one to many one to one one to one laravel own artisan command pagination pagination bootstrap pagination bootstrap php mysql pagination laravel pagination laravel bootstrap pagination links pagination php php php artisan php carbon immutable php framework php framework 2019 php what's new 2019 phpunit phpunit laravel phpunit testing pivot laravel policy laravel polymorphic relationships queue and events queue email queue for laravel queue jobs queue laravel 5.8 registration form relationship laravel eloquent relationship mysql restful controller role permission in laravel roles laravel route model binding laravel routing in laravel save image to database seo friendly seo friendly content writing seo friendly website seo laravel seo optimization simple pagination laravel slugify sqlite relational database sqlite relationships between tables symfony command console symfony laravel tailwind css tailwind laravel mix telescope laravel tutorial laravel unit testing unit testing laravel upload file laravel upload file php upload image laravel upload image to database php upload images laravel upload multiple files in php url slug laravel url slug php vue vue.js vuejs laravel why use laravel queue why use queue