You have by far the most useful tutorials about Laravel. I really don't need 50 videos explaining everything about Laravel. Your approach with actually building websites is much better and you learn more through this.
It's really nice to see the alternative approach to what you could see, say, in Jeffrey Way's videos. It gives you new food for thought and pushes you to be more creative with your project. Thank you for this great series on Laravel ACL. I watched yor Social Network series, too, and liked it a lot, but this one really found me in the right place at the right time. Much props to you for your thorough way of explaining the essentials!
I had trouble finding a good tutorial about roles. Glad I found you! Very nice and clear explanation with a practical example. Got the roles for my project up and running in no time. Thanks so much for this!
Thanks so much for enlightening this topic. Great tutorial!! An idea of ACL I've been trying to implement is a CRUD based permissions. This of course a far more advanced type of ACL, implemented in large scale applications where a super admin can create a list of modules (ex. Users, Companies, Employees ...), a list roles (ex. Admin, Human Resource, Data Clerk ...), attache each role to the entire list of modules with the operations permitted on each module (ex. View, Edit, Delete). I have all the db and relationships in place. And I grouped my routes by method (get, post/put, delete) with a middleware assigned to each group (canView, canEdit, canDelete). The hardest part for me is to find a way to identify which route is associated to which module. I was thinking maybe each module will have a name field and a route URI field, but I don't know of this is going to have some flaw somewhere. I couldn't find any examples out there. I'm hoping that you might be able to extend this tutorial or create an other playlist with a similar example. Thank you again!!
Thanks for teaching me so much stuff! With this tutorial (and other your tutorials) I managed to modify tymon/JWT to do role checking for app that I'm building. GREAT TUT! :D
Erstmal vielen Dank für das tolle Tutorial, ich beschäftige mich erst seit ein paar Wochen mit Laravel und kenne mich daher noch nicht so gut mit dem Framework aus. Daher bin ich froh endlich mal jemand gefunden zu haben der die Sachen verständlich erklärt. Eine Sache habe ich allerdings veränder, und zwar: die Klasse CheckRole public function handle($request, Closure $next, $roles) { if($request->user() === null) { //if not return a response and an error code return response(utf8_encode("Sie besitzen keine Berechtigung für diesen Bereich"), 401); } if($request->user()->hasAnyRole($roles) || !$roles) { //alles ok weiter gehts return $next($request); } return response(utf8_encode("Sie besitzen keine Berechtigung für diesen Bereich"), 401); } so spart man sich einiges an Code kann so nicht nur Routs schützen, Route::get('admin/l', 'AdminController@index')->middleware('roles:Admin'); sondern auch einzelne Klassenabschnitte $this->middleware('roles:Admin'); oder if($this->middleware('roles:Admin') && $this->middleware('roles:Author')) return true; oder if($this->middleware('roles:Admin') || $this->middleware('roles:Author')) return true; Grüße
@if(Auth::user()->hasRole('Admin') == Auth::user()->id) I found this way to use this middleware in @if statement for the views. If the statement is true will be return the id of the user with this role, thanks for the video Mindpsace :D
I do offer courses on Udemy but providing content on RUclips is something I really enjoy. You can freely test different things and don't have to produce entire courses for every bit of information you want to pass. But of course it's great to heat that you're really liking my content! :)
I have an question about the routes. In laravel 5.3 the routes have been changed, if i want to implement this. How do i adjust the CheckRole middleware. I can't give any key values to the routes anymore. So the getAction method can't collect the roles of the user. Any tip how can i adjust the middleware to make it work in Laravel 5.3?
Hi, i encountered the same problem here. The getAction does not include the 'roles' array witch is added in this video. You can pass a parameter by setting (for example) 'middleware' => 'roles:admin' in your routes (web) file. You can access the parameter by setting it in the handle function within your middleware. This is also included in the Laravel documentation.
thanks for your ACL tuto. I did follow the different steps. Is there any difference implementing it with laravel 5.3 ? For example in(1:35) adding the "$user->roles()->attach(Role::where('name', 'User')->first()); in AuthController.php. I suppose it will be added in App\Http\Controllers\Auth\RegisterController.php in the function create, right ? How do you add it ? Thanks again
ok. we can just modify it like this : protected function create(array $data) { $user = User::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => bcrypt($data['password']), ]); $user->roles()->attach(Role::where('name', 'User')->first()); return $user; }
hope you are answering me i'd like to know how to clean way to do it on view as we do this we shall use blade syntax if-else to hide some of those menu to be invisible to other user how can we possibly do it in cleaner way? looking forward to ur response Thanks!
Dear Jasson, You can do that by covering HTML block like @if(Auth::user()->hasAnyRole(['admin', 'author'])) Welcome to the admin panel @endif you can also use hasRole('admin') function if you assign just one role to a user. If My answer helps you, support by channel by subscribing it. I'm going to start advance laravel lectures very soon. (free). Channel "Techno Funkaar" => bit.ly/TechnoFunkaar
Hello and thank you very much for these fantastic videos. I wonder: If I have a table 'payments' and in this table can access two user 'user' and 'administrator' but with one difference, the user can only see the fields 'date' and 'description of payment' instead the administrator can see, 'data', 'description' and 'cost'. 1- To display different fields for different users, do I have to create two controllers in two different routes, es: admin/payments and user/payments ? 2- if 'user' and 'admin' have different rules (policy) for reading, editing, deleting, I will obviously have to create two separate files, one for 'user' and one for 'admin' ... right? Thanks so much !
7 лет назад
great course man! one question though: if my different users has different fields .how is the ideal solution to achieve this? lets say admin has name, email and password author has name, email, password and another field a user with other role would have others fields
It would be interesting to see the work with Elixir, bootstrap connection , the js and that something like this through , for beginners . Or a video you already have , and I overlooked ?
It would be nice to continue the tutorial with solving the multi Auth problem that laravel has. If I am logged in in both frontend and backend and than I logout from backend, the user from the frontend is also logged out because Laravel default auth scaffolding has not been built to differentiate between those. For this, using Gates would be required.
Hi, Your tutorial is great.I just have one question if you would be kind to answer: How do i group the routes by a certain role(Admin for example) using your middleware,do i use the same syntax as like for the web?Is it something like this? Route::group(['middleware'=>'roles',roles=>['Admin']]{ admin route 1 admin route 2 admin route 3 });
Its great to see the videos I am beginner to Laravel and I find it very helpful . Want to thank you for that. My main concern is that in Laravel 5.2 we have make:auth command which create login sign up and forgot password by default. So how we play with that in your videos you have used your technique which one is better to use? And secondly let say I have two roles and I want to redirect each user to different page when they login How Can I achieve this. Looking for your Reply.
Hi, great to hear that you're liking the video! Regarding your question: If you use make:auth, it will still set up the User model which you find in the app/ folder. So you may still edit this and you should be able to get everything to work with this model as well. Regarding the redirect: You could check the user roles in the controller action handling the route and then redirect from there.
Mindspace Thanks , I am glad that you replied . But the concern is that when i use make:auth I am not able to interfere whith laravel's path and auth it does give me the property to set of redirect path to but its not sending to any controller or anything like that so how do I check the role when the laravel authenticate using their auth. because i need to test there whether the role is a or b so I can redirect my desired path. Looking for your help :)
Hi , first of all I would like thank you for this great tutorial. I need little help from you. I need to show the links which are accessible for the specific user role. Like Author Page is accessible to only Admin and Author then I want to show link for the same page only for the Admin And Author Roles group. Thanks again and keep up the good work :)
Hello...First of all great self explaining tutorials. But i encountered a problem Call to undefined method Illuminate\Auth\GenericUser::hasAnyRole() in my checkrole middleware any idea how to solve this.
I use laratrust package. And inside User.php (model) i have this code: public static function boot() { User::created(function ($user) { $user->syncRoles(8); }); } (Everything works, when i create user manualy and if user registers on his own) Can someone confirm its ok? Or i need to change something.
hello dear, how can manager dynamic roles settings (In my project, admin create role according to they want, and assign a every page role to different different user) for users, can you suggest me better
great tutorial but I have a small problem. I did all as the 4 tutorials. when a user logged in, user can access all views they are not approved in db. why is this happend? the thing is before user logged in, they are access denied for every views other than welcome window. it is working correctly. Can you please help
I did every step with the same names and when I check a box, uncheck the other and press the Assign Roles it redirects me to the same page I was in but with the link address of the Assigning Roles function, not the link address of the page which I was in and without any errors, but nothing happens, the role is the same, nothing changed..!
Sir I am facing problem that first i assign Admin, Shopkeeper roles to route group and it works fine then i assign only Admin role but its nor working.
Er ist Kolumbianer und kann kein bisschen Englich sprechen nur ein bisschen lesen, aber er bedankt sich und du hast ihm extrem weitergeholfen :) Das letztere gilt auch für mich
Hello I got an error ErrorException in EloquentUserProvider.php line 114: Argument 1 passed to Illuminate\Auth\EloquentUserProvider::validateCredentials() must be an instance of Illuminate\Contracts\Auth\Authenticatable, instance of App\User given, called in C:\xampp\htdocs\laravel\vendor\laravel\framework\src\Illuminate\Auth\SessionGuard.php on line 385 and defined
+Jacques Rousseauu Hi, you may also specify middleware in your controller, there you can then define which routes/actions should receive that middleware and which should not. Here's a link with more info: laravel.com/docs/5.2/controllers#controller-middleware
+Mindspace when I dd() in CheckRole middleware with $action['roles'], it shows undefined roles index. I inserted the middleware in controller construct method through following code $this->middleware('roles', ['only' => ['create', 'store'], 'roles' =>[2,3]]);
Hello, there I have one problem When Iam using on $request->route()->getAction() it shows error but work in laravel can you tell me how i use this on my lumen project thank you for this Video
Hi, what is the effective way to show/hide nav items based on roles? Right now i'm using if statement for each nav elements. for example for admin nav element i'm using @if(Auth::user()->hasRole('admin')) . and for author nav using @if(Auth::user()->hasAnyRole(['author', 'admin'])) . Is there anyway i can use middleware to show/hide nav elements, cause if there are a lot of nav elements there would be a lot of if statements
No, middleware can only help you when handling requests, but if you want to structure your view, you need to work in your blade templates. You could of course try grouping your nav elements into fewer if statements.
@Mindspace I have another question, if I want to create Users at the same page, how can I do that because there can't be 2 post routes. I have been searching for things, but I couldn't find a solution for it.
Great Tutor!, you've made my day. I have been battling with this issue for days, but hasve finally arrived to the solution through this tutorial Great Work.I have a few question, Can I return a view(page) when a user attempts to view a non-permitted page instead of return a response. I want this so that the page can load the master files and it can be more interrractive instead of a blank page with little message of Insuffiecent Permission. Nonethelees, I did that but here is the erro, maybe i am missing thing?FatalThrowableError in VerifyCsrfToken.php line 156: Call to a member function setCookie() on nullHow can this be corrected or is it not possible to return a view in a middleware?
for those people who cant sign in with their new created users try to change youre postSignUp method on the AuthController : $user->password = $request['password']; to, $user->password = bcrypt($request['password']);
Hi man thanks for the great tutorial .. one question though .. I 've set a default role (user) but I need that role to be set when someone creating a new account ?!?!?! thnx again :P
Is there any way to do it using events ?sign up triggers an event which sets that user_id in the roles model and the default role_id ?It is better to do it like this ?
Dear, Please I have any issue, which is directly relating to this course. I want to be ablet to protect a Resource Route and still allow other route to be seen upon authentication. Only Admin to see other. See my code below and tell me how to implement Denial for other route after authentication once the user does not have that right(role): Main Code public function __construct() { $this->middleware('auth'); $this->middleware('roles')->except('index','show'); } So I want to implement something like this: public function __construct() { $this->middleware('auth'); $this->middleware('roles'=>['Administrator'])->except('index','show'); } But this is not working.What Am I doing wrong.
Im trying to implement it by using make:auth but im getting this error Call to undefined method Illuminate\Database\Query\Builder::hasAnyRoles() in laravel 5.3 please help , if anyone has implemented user roles by make:auth please reply
Great tutorial! It was exactly this, what I was looking for. Well explained! :) But what about SoftDeletes? When I soft-delete an relation between an user and a role, the deleted_at timestamp is set. But the public function roles() in the User model is still retrieving them. Shouldn't they be excluded from the list? See below example: $users = User::get(); foreach($users as $user) { echo "User roles for " . $user->email . ":"; echo ""; foreach($user->roles as $role) { echo "" . $role->name . ""; } echo ""; } Only when I fully delete the soft-deleted row from the "user_has_roles" mapping table, the role is excluded. It should be already excluded, when the row is soft-deleted.
i have implimented the ACL as shown by you, lot of thanks for this, but i request that please create a video tutorial for 3 more features 1 email activation after register 2 blocking and unblocking users by admin account on boolean status field value in user table 3. how and where to redirect users to different dashboards after login using ACL as shown by you. This would be of great help please help me out.... Thanks
Hey, thanks for this video tutorial. I want to use custom middleware in controller construct function to allow only admin and author, not in root. How to do that? I try in controller __construct: $this->middleware('roles' => ['admin', 'author']); but this show error. How to use middleware that you created, in controllers?
The problem is, that the middleware set up here, uses additional values set up in the routes config (the roles). You may try this code (I didn't test it, not sure if it works): $this->middleware('roles:admin,author');
Thanks for quick reply. I try this. There is no error but middleware doesn't work. It also allow access to user with role name "vistor". I create three users with: admin, author and visitor roles Each of them have only one role. And all of theme have access with: $this->middleware('roles:admin,author'); I don't know why. This should allow access only for admin and author, but I can visit pages also logged in as visitor. Can I solve this problem creating goup "roles" with this two role? If can, is that a good solution? What do you think?
That certainly would be solution and there would be nothing wrong with it. To make the other solution work, you would need to re-write the middleware to be able to receive and handle parameters there.
I mean when I have radio buttons, I have to give them the same name but that contains role_... so I can't switch when I have radio buttons or is there a method that I still can switch that I don't need the same names?
You may use the approach here (create your own middleware) and adjust the User Model, which you use with Laravel's built in auth system as well, like shown in the videos. That should work in my opinion
How can I ask what role the user have like with this I can ask the username: {{ucfirst(Auth::user()->name)}} But how can I ask the name of the user_role
I can't resolve this error . Please help FatalErrorException in CheckRole.php line 25: Call to undefined method Illuminate\Auth\GenericUser::hasAnyRole()
Please check my source code (link in video description, choose the right branch there). By comparing it to yours, you should be able to find out what goes wrong.
Thank you So much Sir. I resolve my error . I forgotten to mention "use App\Http\Middleware\CheckRole;" in Kernel.php. Thanks for replying me . God bless you Sir
Thanks for being honest but just suggestion it would be great if you also make tutorial for redis using laravel these are some complex topics so it will be helpful for everyone because you explain very well and in detail Thanks again ...
If you want to protect routes against unauthorized access, you may have a look at Laravel middleware. Have a look at my "Social Network" series, I do cover middleware there, too
Hey, It's really useful. I'm using make:auth How can I attach role in this case, protected function create(array $data) { return User::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => bcrypt($data['password']), ]); } This line not work when I add it. $this->attach(Role::where('name', 'User')->first()),
+Mindspace That code from Issam is from the authcontroller and that is where the user is been created. So how can we combine your code with that laravel provides us with?
but i guess Gates and Policy is much better than normal middleware spicelly if you want to create role for users table can create update delete read every one has role so i guess Gate and Policy is much easer to deal with
Dear, Please I have any issue, which is directly relating to this course. I want to be ablet to protect a Resource Route and still allow other route to be seen upon authentication. Only Admin to see other. See my code below and tell me how to implement Denial for other route after authentication once the user does not have that right(role): Main Code public function __construct() { $this->middleware('auth'); $this->middleware('roles')->except('index','show'); } So I want to implement something like this: public function __construct() { $this->middleware('auth'); $this->middleware('roles'=>['Administrator'])->except('index','show'); } But this is not working.What Am I doing wrong.
You have by far the most useful tutorials about Laravel. I really don't need 50 videos explaining everything about Laravel. Your approach with actually building websites is much better and you learn more through this.
Great all tutorials from 1 to 4!!! Thanks for explain it highly clear! We need people like you in this world
Don't know what to say ... thanks so much Jordi, I'm really glad that this was helpful to you! :)
absolutely agree on this. I know nothing about ACL and after just this 4 video, i understand it. Thanks man.
This is the most elegant solution i have found on RUclips.
It's really nice to see the alternative approach to what you could see, say, in Jeffrey Way's videos. It gives you new food for thought and pushes you to be more creative with your project. Thank you for this great series on Laravel ACL. I watched yor Social Network series, too, and liked it a lot, but this one really found me in the right place at the right time. Much props to you for your thorough way of explaining the essentials!
+Revolted Child
Wow, many thanks for these very kind words! I'm really happy to hear you're finding this video series helpful :)
I had trouble finding a good tutorial about roles. Glad I found you! Very nice and clear explanation with a practical example. Got the roles for my project up and running in no time. Thanks so much for this!
+Nikolay K.
Awesome to hear Nikolay! :)
You are the best man. This thing i have really struggled with it but with this series, i feel now like a star. Thanks man
So awesome to hear that Charles, thanks a lot!
Man, you´ve made it so easy, appreciate all the efforts on these seriers, they are really cool!
I'm really glad to hear that, thank you so much Jose!
Thanks so much for enlightening this topic. Great tutorial!! An idea of ACL I've been trying to implement is a CRUD based permissions. This of course a far more advanced type of ACL, implemented in large scale applications where a super admin can create a list of modules (ex. Users, Companies, Employees ...), a list roles (ex. Admin, Human Resource, Data Clerk ...), attache each role to the entire list of modules with the operations permitted on each module (ex. View, Edit, Delete). I have all the db and relationships in place. And I grouped my routes by method (get, post/put, delete) with a middleware assigned to each group (canView, canEdit, canDelete). The hardest part for me is to find a way to identify which route is associated to which module. I was thinking maybe each module will have a name field and a route URI field, but I don't know of this is going to have some flaw somewhere. I couldn't find any examples out there. I'm hoping that you might be able to extend this tutorial or create an other playlist with a similar example. Thank you again!!
Thanks again ! - The clearest ACL tutorial on the net.
Thanks so much, really amazing to hear that!
very easy and useful acl tutorial. Was searching like this since longer.
Happy to hear that this was helpful Mohd! :)
Thanks for teaching me so much stuff! With this tutorial (and other your tutorials) I managed to modify tymon/JWT to do role checking for app that I'm building. GREAT TUT! :D
Thanks so much for sharing this, it makes me really happy to read that the videos helped you :)
Thanks!! Its been a bit tricky to make it work on my existing authentication but it works like a charm.
Happy to read that the video was helpful for you, thank you for sharing this!
Thank you verymuch. Although my English listening skill is not good. But I can finish your tutorial completely.
Thank you.
In case of Laravel 5.5, the auth controller dissapears. How should we proceed?
Erstmal vielen Dank für das tolle Tutorial, ich beschäftige mich erst seit ein paar Wochen mit Laravel und kenne mich daher noch nicht so gut mit dem Framework aus.
Daher bin ich froh endlich mal jemand gefunden zu haben der die Sachen verständlich erklärt.
Eine Sache habe ich allerdings veränder, und zwar:
die Klasse CheckRole
public function handle($request, Closure $next, $roles)
{
if($request->user() === null) {
//if not return a response and an error code
return response(utf8_encode("Sie besitzen keine Berechtigung für diesen Bereich"), 401);
}
if($request->user()->hasAnyRole($roles) || !$roles) {
//alles ok weiter gehts
return $next($request);
}
return response(utf8_encode("Sie besitzen keine Berechtigung für diesen Bereich"), 401);
}
so spart man sich einiges an Code kann so nicht nur Routs schützen,
Route::get('admin/l', 'AdminController@index')->middleware('roles:Admin');
sondern auch einzelne Klassenabschnitte
$this->middleware('roles:Admin');
oder
if($this->middleware('roles:Admin') && $this->middleware('roles:Author')) return true;
oder
if($this->middleware('roles:Admin') || $this->middleware('roles:Author')) return true;
Grüße
Hi Philipp,
freut mich, dass es gefällt! Und vielen Dank für deinen Verbesserungsvorschlag - sieht gut aus, danke fürs Teilen!
@if(Auth::user()->hasRole('Admin') == Auth::user()->id)
I found this way to use this middleware in @if statement for the views. If the statement is true will be return the id of the user with this role, thanks for the video Mindpsace :D
again superlike after social network...exactly what I was looking for..I became big fan of you ..thank you :)
+Nirav Jobanaputra
That's so awesome to hear, many, many thanks Nirav! :)
+Mindspace hey why dont you start your paid service when you are better then paid?
I do offer courses on Udemy but providing content on RUclips is something I really enjoy. You can freely test different things and don't have to produce entire courses for every bit of information you want to pass. But of course it's great to heat that you're really liking my content! :)
I have an question about the routes. In laravel 5.3 the routes have been changed, if i want to implement this. How do i adjust the CheckRole middleware. I can't give any key values to the routes anymore. So the getAction method can't collect the roles of the user. Any tip how can i adjust the middleware to make it work in Laravel 5.3?
Hi, i encountered the same problem here. The getAction does not include the 'roles' array witch is added in this video. You can pass a parameter by setting (for example) 'middleware' => 'roles:admin' in your routes (web) file. You can access the parameter by setting it in the handle function within your middleware. This is also included in the Laravel documentation.
Very helpful and nice way to perform users role. Great job. Thx from France ;)
+Frédéric Lossignol
Merci beaucoup Frédéric!
Love your tutorial. Great! Will check out more tutorials/courses you've made! thank you!
Realyl great to hear that - enjoy all the videos on the channel! :)
awesome finally you show us how to make roles. thank you very much :)
+Demonz312
Very happy to hear that it's helpful and you're liking it :)
Excellent tutorial of ACL / Roles, Thanks a lot
Awesome to hear, thank you! :)
thanks for your ACL tuto. I did follow the different steps. Is there any difference implementing it with laravel 5.3 ? For example in(1:35) adding the "$user->roles()->attach(Role::where('name', 'User')->first()); in AuthController.php. I suppose it will be added in App\Http\Controllers\Auth\RegisterController.php in the function create, right ? How do you add it ? Thanks again
ok. we can just modify it like this :
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
$user->roles()->attach(Role::where('name', 'User')->first());
return $user;
}
This is what I"m looking for.. thanks sir..
hope you are answering me
i'd like to know how to clean way to do it on view
as we do this we shall use blade syntax if-else to hide some of those menu to be invisible to other user
how can we possibly do it in cleaner way?
looking forward to ur response
Thanks!
Dear Jasson, You can do that by covering HTML block like
@if(Auth::user()->hasAnyRole(['admin', 'author']))
Welcome to the admin panel
@endif
you can also use hasRole('admin') function if you assign just one role to a user.
If My answer helps you, support by channel by subscribing it. I'm going to start advance laravel lectures very soon. (free). Channel "Techno Funkaar" => bit.ly/TechnoFunkaar
i love how you teach in video, keep it up man!
Many thanks for the amazing feedback!
Hello and thank you very much for these fantastic videos.
I wonder: If I have a table 'payments' and in this table can access two user 'user' and 'administrator' but with one difference, the user can only see the fields 'date' and 'description of payment' instead the administrator can see, 'data', 'description' and 'cost'.
1- To display different fields for different users, do I have to create two controllers in two different routes, es: admin/payments and user/payments ?
2- if 'user' and 'admin' have different rules (policy) for reading, editing, deleting, I will obviously have to create two separate files, one for 'user' and one for 'admin' ... right?
Thanks so much !
great course man! one question though: if my different users has different fields .how is the ideal solution to achieve this?
lets say admin has name, email and password
author has name, email, password and another field
a user with other role would have others fields
It would be interesting to see the work with Elixir, bootstrap connection , the js and that something like this through , for beginners . Or a video you already have , and I overlooked ?
+Никита Лощенин
No, I don't have content on that yet. I might some on these topics, I'll see. It is noted :)
As usual an useful video from you.Thanks for the great session! :)
+Soft Pdf
Thank you so much!
Thank for this awesome tutorials.
It would be nice to continue the tutorial with solving the multi Auth problem that laravel has. If I am logged in in both frontend and backend and than I logout from backend, the user from the frontend is also logged out because Laravel default auth scaffolding has not been built to differentiate between those. For this, using Gates would be required.
Awesome series bro
Thanks so much!
Hi,
Your tutorial is great.I just have one question if you would be kind to answer:
How do i group the routes by a certain role(Admin for example) using your middleware,do i use the same syntax as like for the web?Is it something like this?
Route::group(['middleware'=>'roles',roles=>['Admin']]{
admin route 1
admin route 2
admin route 3
});
Its great to see the videos I am beginner to Laravel and I find it very helpful . Want to thank you for that.
My main concern is that in Laravel 5.2 we have make:auth command which create login sign up and forgot password by default. So how we play with that in your videos you have used your technique which one is better to use?
And secondly let say I have two roles and I want to redirect each user to different page when they login How Can I achieve this.
Looking for your Reply.
Hi, great to hear that you're liking the video!
Regarding your question: If you use make:auth, it will still set up the User model which you find in the app/ folder. So you may still edit this and you should be able to get everything to work with this model as well.
Regarding the redirect: You could check the user roles in the controller action handling the route and then redirect from there.
Mindspace Thanks , I am glad that you replied . But the concern is that when i use make:auth I am not able to interfere whith laravel's path and auth it does give me the property to set of redirect path to but its not sending to any controller or anything like that so how do I check the role when the laravel authenticate using their auth. because i need to test there whether the role is a or b so I can redirect my desired path.
Looking for your help :)
You should still be able to define the additional methods used in this video as my User doesn't really differ from Laravel's default User.
Hi , first of all I would like thank you for this great tutorial. I need little help from you.
I need to show the links which are accessible for the specific user role. Like Author Page is accessible to only Admin and Author then I want to show link for the same page only for the Admin And Author Roles group.
Thanks again and keep up the good work :)
Hello...First of all great self explaining tutorials.
But i encountered a problem
Call to undefined method Illuminate\Auth\GenericUser::hasAnyRole()
in my checkrole middleware
any idea how to solve this.
I use laratrust package.
And inside User.php (model) i have this code:
public static function boot()
{
User::created(function ($user) {
$user->syncRoles(8);
});
}
(Everything works, when i create user manualy and if user registers on his own)
Can someone confirm its ok? Or i need to change something.
Thanks for your kind explanation.
This is very good video.
I sincerely hope to give this code source.
hello dear, how can manager dynamic roles settings (In my project, admin create role according to they want, and assign a every page role to different different user) for users, can you suggest me better
great tutorial but I have a small problem. I did all as the 4 tutorials. when a user logged in, user can access all views they are not approved in db. why is this happend? the thing is before user logged in, they are access denied for every views other than welcome window. it is working correctly.
Can you please help
I did every step with the same names and when I check a box, uncheck the other and press the Assign Roles it redirects me to the same page I was in but with the link address of the Assigning Roles function, not the link address of the page which I was in and without any errors, but nothing happens, the role is the same, nothing changed..!
Can I use this with my route having the user id as parameter?
Sir I am facing problem that first i assign Admin, Shopkeeper roles to route group and it works fine then i assign only Admin role but its nor working.
Need some help!! How to set default user role if I am using automatically generated authentication?
soy colombiano no se hablar en ingles para lo se leer de una manera básica pero créame que este video me ayudo thanks
Er ist Kolumbianer und kann kein bisschen Englich sprechen nur ein bisschen lesen, aber er bedankt sich und du hast ihm extrem weitergeholfen :)
Das letztere gilt auch für mich
Dann vielen, vielen Dank an euch beide - auch für die Übersetzung!
¡Muchas gracias!
igualmente me ayudo tambien
Hello I got an error
ErrorException in EloquentUserProvider.php line 114:
Argument 1
passed to Illuminate\Auth\EloquentUserProvider::validateCredentials()
must be an instance of Illuminate\Contracts\Auth\Authenticatable,
instance of App\User given, called in
C:\xampp\htdocs\laravel\vendor\laravel\framework\src\Illuminate\Auth\SessionGuard.php
on line 385 and defined
Great tutorial.
how can I use middleware and role, when i am using RESTful Resource Controllers....
+Jacques Rousseauu
Hi, you may also specify middleware in your controller, there you can then define which routes/actions should receive that middleware and which should not. Here's a link with more info: laravel.com/docs/5.2/controllers#controller-middleware
+Mindspace when I dd() in CheckRole middleware with $action['roles'], it shows
undefined roles index. I inserted the middleware in controller construct method through following code $this->middleware('roles', ['only' => ['create', 'store'], 'roles' =>[2,3]]);
You should be able to pass parameters like this: $this->middleware('roles:PARAMS', ...);
+Jacques Rousseauu ahesanalisuthar.wordpress.com/2015/06/04/laravel-5-1-pass-middleware-parameters-as-array/
Hello, there I have one problem When Iam using on $request->route()->getAction() it shows error but work in laravel can you tell me how i use this on my lumen project thank you for this Video
Hi, what is the effective way to show/hide nav items based on roles? Right now i'm using if statement for each nav elements. for example for admin nav element i'm using @if(Auth::user()->hasRole('admin')) . and for author nav using @if(Auth::user()->hasAnyRole(['author', 'admin'])) . Is there anyway i can use middleware to show/hide nav elements, cause if there are a lot of nav elements there would be a lot of if statements
No, middleware can only help you when handling requests, but if you want to structure your view, you need to work in your blade templates. You could of course try grouping your nav elements into fewer if statements.
@Mindspace I have another question, if I want to create Users at the same page, how can I do that because there can't be 2 post routes. I have been searching for things, but I couldn't find a solution for it.
What do you mean with "can't be 2 post routes "? You may of course have two forms on one page
Great Tutor!, you've made my day. I have been battling with this issue for days, but hasve finally arrived to the solution through this tutorial Great Work.I have a few question, Can I return a view(page) when a user attempts to view a non-permitted page instead of return a response. I want this so that the page can load the master files and it can be more interrractive instead of a blank page with little message of Insuffiecent Permission. Nonethelees, I did that but here is the erro, maybe i am missing thing?FatalThrowableError in VerifyCsrfToken.php line 156:
Call to a member function setCookie() on nullHow can this be corrected or is it not possible to return a view in a middleware?
You can redirect requests in middleware. So you can create a route which then in the end returns the view to which you redirect.
Thank you very much. It works well. I thumb up for you
awesome guide!
It's really great to hear that you enjoyed it! :)
Hello I am getting this error
Call to a member function roles() on null
I am stuck on it. any help????
I'm having the same problem. Have you figured it out?
the same here :/
Great tutorial Its very helpful... Thanks a ton... :)
Thank you! :)
for those people who cant sign in with their new created users try to change youre postSignUp method on the AuthController :
$user->password = $request['password']; to, $user->password = bcrypt($request['password']);
How can i assing roles array as dynamic from database ?
Hi man thanks for the great tutorial .. one question though .. I 've set a default role (user) but I need that role to be set when someone creating a new account ?!?!?! thnx again :P
Hi Karolos, simply set/ overwrite your default role in the user-sign-up controller action then :)
Is there any way to do it using events ?sign up triggers an event which sets that user_id in the roles model and the default role_id ?It is better to do it like this ?
Yes, this is of course also possible. Have a look at the official docs->events. They're written really well and should get you started.
Thanks Man I'll have a look to the docs!Ijust wanted to be sure that it's possible :D
How can I use this in view blade ? @if ( ! Auth::check() && hasRole('Admin') ) ?
Dear, Please I have any issue, which is directly relating to this course. I want to be ablet to protect a Resource Route and still allow other route to be seen upon authentication. Only Admin to see other. See my code below and tell me how to implement Denial for other route after authentication once the user does not have that right(role):
Main Code
public function __construct()
{
$this->middleware('auth');
$this->middleware('roles')->except('index','show');
}
So I
want to implement something like this:
public function __construct()
{
$this->middleware('auth');
$this->middleware('roles'=>['Administrator'])->except('index','show');
}
But this is not working.What Am I doing wrong.
Im trying to implement it by using make:auth but im getting this error Call to undefined method Illuminate\Database\Query\Builder::hasAnyRoles() in laravel 5.3 please help , if anyone has implemented user roles by make:auth please reply
I used eloquent and encountered the same problem ...have you figured it out
Great tutorial! It was exactly this, what I was looking for. Well explained! :)
But what about SoftDeletes?
When I soft-delete an relation between an user and a role, the deleted_at timestamp is set. But the public function roles() in the User model is still retrieving them. Shouldn't they be excluded from the list?
See below example:
$users = User::get();
foreach($users as $user) {
echo "User roles for " . $user->email . ":";
echo "";
foreach($user->roles as $role) {
echo "" . $role->name . "";
}
echo "";
}
Only when I fully delete the soft-deleted row from the "user_has_roles" mapping table, the role is excluded. It should be already excluded, when the row is soft-deleted.
i have implimented the ACL as shown by you, lot of thanks for this,
but i request that please create a video tutorial for 3 more features
1 email activation after register
2 blocking and unblocking users by admin account on boolean status field value in user table
3. how and where to redirect users to different dashboards after login using ACL as shown by you.
This would be of great help please help me out.... Thanks
Will you please share implemented ACL code.......email id: mr.malikfayyaz@gmail.com
Many thanks for your suggestions! I can't promise anything, but I'll keep them in mind.
Help me !!
i using form in table not send while submit form.
Hey, thanks for this video tutorial. I want to use custom middleware in controller construct function to allow only admin and author, not in root. How to do that? I try in controller __construct: $this->middleware('roles' => ['admin', 'author']); but this show error. How to use middleware that you created, in controllers?
The problem is, that the middleware set up here, uses additional values set up in the routes config (the roles). You may try this code (I didn't test it, not sure if it works):
$this->middleware('roles:admin,author');
Thanks for quick reply. I try this. There is no error but middleware doesn't work. It also allow access to user with role name "vistor". I create three users with: admin, author and visitor roles Each of them have only one role. And all of theme have access with: $this->middleware('roles:admin,author'); I don't know why. This should allow access only for admin and author, but I can visit pages also logged in as visitor.
Can I solve this problem creating goup "roles" with this two role? If can, is that a good solution? What do you think?
That certainly would be solution and there would be nothing wrong with it.
To make the other solution work, you would need to re-write the middleware to be able to receive and handle parameters there.
Thanks man. Your videos are very useful. You help me a lot.
Awesome to hear, thank you! :)
Hi thanks very much for this but here i'm stacked infront this problem
Call to a member function roles() on null
can u help me out please ?
i'm using it like this :
i dont understand why u put the type="hidden" instead of type="email"?
and please tell me what is the matter with my code
ok tanks so much Vignesh i get it :)
it works Vignesh Sivakumar thank you so much
5.3
Does the input type has to be a checkbox or is there a way to make it a radio button, because it is not able to change the name or can I ?
Hi, you may of course setup your form the way you want.
I mean when I have radio buttons, I have to give them the same name but that contains role_... so I can't switch when I have radio buttons or is there a method that I still can switch that I don't need the same names?
You simply have to extract the value on your backend ($request->input('radio-button-name'). Then this will be your role name for example
big help, thanks a lot
Great to hear that! :)
Hello,
How can I add a standard user role when I use the basic Laravel Auth system?
You may use the approach here (create your own middleware) and adjust the User Model, which you use with Laravel's built in auth system as well, like shown in the videos. That should work in my opinion
Mindspace It was a problem at my side... I had primary key on the id in user_roles but I missclicked on that, had to be auto increment
How can I ask what role the user have like with this I can ask the username: {{ucfirst(Auth::user()->name)}} But how can I ask the name of the user_role
In your user model, you simply need to implement the respective method which fetches this. Then, you can access it on the Auth::user() object.
Nice one thanks.
Happy to hear that you liked it! :)
You are a GOD
YOU are Kanishka, thank you very much for your great feedback!
I can't resolve this error . Please help
FatalErrorException in CheckRole.php line 25:
Call to undefined method Illuminate\Auth\GenericUser::hasAnyRole()
Please check my source code (link in video description, choose the right branch there). By comparing it to yours, you should be able to find out what goes wrong.
Thank you So much Sir. I resolve my error . I forgotten to mention "use App\Http\Middleware\CheckRole;" in Kernel.php. Thanks for replying me . God bless you Sir
Great Can you please make a tutorial on memcache using laravel...
Thanks for your suggestion! I don't plan on creating content on this in the near future to be honest, but you never know
Thanks for being honest but just suggestion it would be great if you also make tutorial for redis using laravel these are some complex topics so it will be helpful for everyone because you explain very well and in detail Thanks again ...
Thanks man
after logged it's still allow to login. how to protect this guide?
If you want to protect routes against unauthorized access, you may have a look at Laravel middleware. Have a look at my "Social Network" series, I do cover middleware there, too
very helpful. Thanks
Great to read that, thank you for your comment :)
The way I see it, one user can only have one role at a time. Right? So why check boxes? Perhaps a many to many is not even necessary.
thanks bro
thank you!
Thank YOU for your comment!
thanks man
Thank YOU for your comment Awar!
Hey,
It's really useful.
I'm using make:auth
How can I attach role in this case,
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
This line not work when I add it.
$this->attach(Role::where('name', 'User')->first()),
+ISSAM MOUSLEH Can you post the code of the User model file?
+Mindspace That code from Issam is from the authcontroller and that is where the user is been created. So how can we combine your code with that laravel provides us with?
I didn't test it, but you should be able to edit the User model just like shown in the video and then use it in the same way.
Change the code in the RegisterController (app\Http\Controllers\Auth\RegisterController.php), something like this:
protected function create(array $data)
{
$user = new User();
$user->name = $data['name'];
$user->email = $data['email'];
$user->company = $data['company'];
$user->password = Hash::make($data['password']);
$user->save();
$user->roles()->attach(Role::where('name', 'guest')->first());
return $user;
}
but i guess Gates and Policy is much better than normal middleware spicelly if you want to create role for users table can create update delete read every one has role so i guess Gate and Policy is much easer to deal with
Is it better to use Policies for this kind of job instead of middlewares and functions in eloquent models? Seems too complicated and bloated
Isn't this tutorial more about RBAC instead of ACL?
I think this is correct, though as you'll often times encounter the term ACL in similar use cases I chose to stick to the more "popular" one
hope help
تاج راسي
??
can I use a route::group for this?
Dear, Please I have any issue, which is directly relating to this
course. I want to be ablet to protect a Resource Route and still allow
other route to be seen upon authentication. Only Admin to see other. See
my code below and tell me how to implement Denial for other route after
authentication once the user does not have that right(role):
Main Code
public function __construct()
{
$this->middleware('auth');
$this->middleware('roles')->except('index','show');
}
So I
want to implement something like this:
public function __construct()
{
$this->middleware('auth');
$this->middleware('roles'=>['Administrator'])->except('index','show');
}
But this is not working.What Am I doing wrong.