Laravel Roles and Permissions: All CORE Things You Need To Know

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello guys i received quite a lot of questions and comments on this youtube channel about gates permission roles and authorizations and relate to topics in laravel so i decided to shoot a separate video covering the basics of how to use gates policies permissions and roles in laravel in whatever starter kit you use whether it's laravel breeze or ui or jet stream the basis is still the same and we will cover a few different examples in this video so separation of user and admin area or having the same area and using gates for separating who can do what so for example simple user can view the data and admin can manage the data so how to make those buttons visible and protect that on the back end as well so let's go our first example about rows is what if you want to separate totally separate admin area and user area with totally different functionality totally different urls functions and everything so for example admin could see the tasks for all users there's a database of tasks so the url is admin tasks the menu is only for admin and separately i've opened that in a different browser user has their own slash user slash tasks with only their tasks so they are separate controllers separate routes separate everything how to implement that i've performed that based on laravel breeze starter kit and let me show you the code quickly about database structure we have task model every task may belong to a user then user has many tasks it's a has menu relationship and then in users table we have a field called is admin it's basically a boolean field for user whether it's admin or not as simple as that so we don't have any roles we have two rows admin and not admin and it is described in one field which is in a separate migration boolean is admin as false and then we use that is admin field in the middleware so i've created php artisan make middleware is admin middleware custom class with this check so if there's no user or if user is not admin we abort with forbidden code 403 then i register that middleware in app http kernel file like this and then i have a name is admin which i can use then in the route and let's look at the routes in route swept i've created two routes for task list for admin and for task list for user and i've created two controllers specifically with the same name of file and class but with different namespace it's a pretty typical scenario so if you are separating admin and user you should separate everything subfolder namespaces routes views everything so let's take a look first you have one route group of middleware auth basically logged in users access all of those and then you have two subgroups one subgroup is for admin another is for user what are the parameters of that route group prefix admin stands for the url prefix which means that if i open that in the browser the url is slash admin slash tasks and for user group the prefixes user and then here i use that middleware of this admin which i've mentioned just a minute ago which means that all of those routes inside here will be accessible only for administrator and also there's a third parameter as admin dot just for route names so in the navigation or anywhere i can reference that route as admin dot as a prefix so then i don't need to repeat the name of admin tasks index instead of doing that here i do that for all the route group and then inside i do controllers as i want so this is just an example of one controller there's an admin tasks controller if we take a look at the controller subfolder there's an admin subfolder and user subfolder and inside of that controller we see namespace of controller's admin so again it's a simplified example but then in the future that admin subfolder may have like 50 controllers and user may have 50 controllers but they are totally separate in their subfolder and namespace and then for admin we get all the tasks order by due date with the user and show that to the admin again the views are also separated admin tasks index if we take a look on the left hand side resources views admin tasks index and then there's a user tasks index if we go to that admin tasks index both of them actually are simple tables extending the same app layout by laravel breeze but admin sees the user and simple user sees only their tasks so they don't see the user and in the controller of user task controller let's open it up i see auth user tasks so only my own tasks by logged in user so this is in short how you separate two totally different areas admin area and user area and they may have different designs so for example in admin index blade you may extend not x app layout so not layouts app from laravel breeze this one but you can create a separate layouts admin or something like that so all the files inside of resources views admin could have different layout our second example about roles and permissions is what if you have one page but with different permissions for different users we will base it on the same is admin field in the database so again two rows users and admins but we don't have rows as database model or database table instead we have is admin field and we will use gates with add can in the blade here to visualize the buttons so here i'm logged in as a simple user i just see the task list but if i'm logged in as admin i see three buttons add new task edit and delete how to implement that one in the blade file if we open that we have add can with different permissions so basically laravel gates is another word for permission so tasks create there's a permission name i came up with it myself it's not from laravel and then for every row there are two more permissions tasks edit and tasks delete where do i define them i define them in auth service provider so in the auth service provider boot method you define as many permissions as you want so tasks create and this callback function should return true or false this by the way short function syntax appeared in php 7.4 is just a shorter way of doing the same thing of function like this and then return return user is admin like this so to save some symbols you can do it in a shorter way like this with php 7.4 but basically you define as many permissions as you want you don't have any middlewares the routes are the same so route with middleware auth leads to the same controller method the method is only one task controller index so there's no permission for list but there are permissions with using can blade command in the blade now of course the protection should come not only in the blade in the index blade with can so not just showing and hiding the buttons but also from the back end if someone guesses the url the protection should be here as well and you can reuse the same gates with this authorized in the beginning of every method so tasks create is the same name called ability as in the can command in the index so task delete tasks create and tasks edit so all over the controller we have tasks create here in the create and store method it's a typical resource controller for edit we authorize for tasks edit and for the destroy its tasks delete so each permission each ability is for their respected function so if i log in as a user and i don't see the button but i may guess the url of tasks create i still get 403 because in the controller we have this authorized of this line so if you have just a few permissions for different functions you can define them in auth service provider and reuse in all your application our third example is similar to the second example but for bigger applications so imagine if you define the gates one by one in auth service provider and you have like 20 cruds with different abilities it may be quite a big list in the end and how to make it shorter to do that laravel has a concept of policies basically grouping those permissions by model so we can create one policy called task policy and assign those methods inside so we run the command php artisan make policy task policy dash dash model task and inside of that we have these methods that i've defined already create update and delete and they all return basically the same thing as those gates so is admin are not but we can delete the gates the policies are discovered automatically since level 7 i think i don't remember before that you had to assign the model to the policy but if your policy is according to the rules of model and then policy it should be discovered automatically so you don't need to register it anywhere and then the syntax changes so in task controller here instead of this authorized tasks create we authorize create so ability and task class what class what eloquent model is our target so create here is the same name as this method in the policy and then also we can authorize not just create any task but whether i can update a specific task so not just task class class name but specific task for edit same thing update task specific task and delete specific tasks and what it allows us to do we can customize the policy methods with another parameter of specific task so for example i can update the task if i'm administrator or if the task belongs to me so or task user id equals auth id actually let's check if the auth exists so auth check and user id equals this one so now if i refresh the table beam as a simple user we refresh and i should see some buttons here so those tasks that are assigned to me i can edit those and also in the blade file in the index blade we change the syntax to can update can delete of specific tasks or can create also we're providing the class name here so if you have permissions or gates related to one eloquent model with typical resource tasks like update delete and create and stuff like that you can group them into policies to manage them more conveniently instead of listing all of them in auth service provider and here's where we get to the concept of roles so what if you have not only admin and user but some other roles like manager or supervisor or something like that you probably would need to create a separate table like rows here user administrator and manager and then assign the user's role id field so in addition or instead of is admin you would have role id2 for administrator and then for example 10 simple users with relay d1 and then how to check those rows in fact there's no difference how you check in the same policies or gates you just change the condition instead of having user is admin in the policy you would have something like this in the create you would compare to role id 2 or role id in 2r3 or something like that so for example create can be done only by admin but updating can be done by an array role id of array of two or three like this so is it admin or manager or the author of the task itself and then nothing really changes in the controllers or blades you just use the same abilities to check create the task and update the task and delete the task now this approach has a bit of inconvenience or disadvantage that you need to deal with numbers here so for any new developer it would not be clear whether it's admin or not of course you can check user role name something like that but then it means that it has to load additional relationship which may be a performance issue a better way if you totally know what are the ids of the rows because if you see them in my case i've seated them in database header roles editor like this and in the fresh database it should be one two and three ids you can assign them to some kind of constants for example in the role model i've created three constants is user is admin or is manager and then instead of those numbers anywhere you need for example in the policies you could write role is admin and this is much more readable and same here role is admin or role is manager something like that and here role is admin and you don't need the comments anymore so this is more readable way and we implemented the roles without too many changes in the policies and engage themselves just checking the permission not by is admin field but instead by role id field and if you want one user to have multiple roles of course then you need to have belongs to menu relationship role user pivot table and then here you would have a different condition of checking whether at least one role of the user corresponds to this one so this is the basics of rows and permissions that come with laravel without any extra packages without any extra starter kits so i've used laravel breeze here only as an example the same logic would work with laravel jetstream laravel ui your own custom starter kit because the files of controllers policies gates and providers are in any starter kit and your personal implementation would be changed only where you use add can or other syntax commands but how you create the rows and permissions and how you check them is inside of laravel files no matter what starter kit you use and of course rows and permissions may be much much more complex and i talk a little more about that in my course on laravel daily.teachable.com if you scroll down there is a course about practical rows and permissions in laravel it's quite a quick course but it touches a bit more on more complex scenarios so these two parts are basically covered in that video in a shorter version so gates permissions and is admin and these two things i will zoom it in a bit so multiple organizations or single organizations it's basically dividing users into teams or organizations or locations whatever you call that and this has much more logic and also another question how to make the permissions dynamic to save them in the database and hear where you could use packages like spotty permissions or bouncer and there are a few more those two probably are the most popular so you can enroll in one course which is 19 with v80 or you can opt in for a yearly membership which i currently advertise and promote everywhere because for 99 per year plus vat if you're from europe you get all those courses which is 19 courses at the moment from what i remember and also everything i release a year ahead so that's quite a good deal if you ask me and if i haven't covered something important about roles and permissions and you have questions shoot in the comments i may shoot a part two of this video for free on youtube or maybe a separate series about rows and permissions or separate hk's so help me with your ideas to shoot more videos for free on this youtube channel and see you guys in other videos
Info
Channel: Laravel Daily
Views: 44,490
Rating: 4.9764981 out of 5
Keywords:
Id: kZOgH3-0Bko
Channel Id: undefined
Length: 16min 31sec (991 seconds)
Published: Wed May 26 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.