I've been tinkering with my own user authorisation and providing user roles based on a database entry for my users
.
I made two roles; a user
role which is just a general, signed up user, and an author
role, which is obviously for an author.
In my users table migration, I'm using $table->string('role')->default('user');
.
In my User.php
, I set up two public functions that calls the role database entry in my users table, like so:
public function isUser()
{
if (Auth::guest()) return false;
return Auth::user()->role = $this->role == 'user';
}
public function isAuthor()
{
if (Auth::guest()) return false;
return Auth::user()->role = $this->role == 'author';
}
Which I can now call in my templates, like so:
@if($user->isUser())
...
@endif
@if($user->isAuthor())
...
@endif
This gives me the control I expect, but I'm not entirely sold on the fact 'it's that easy'. I understand that yes, I can create a relationship with the User and bind the relationship between two models, but I found this pretty neat. My only worry on this is security.
This may not be best practise by a long shot, but I'm fairly new to Laravel and was wondering what security implications doing it the way I have done vs. other methods available.
My last questions are, should I want to provide Route filters, can i do this using my method implemented above and, should I be using before
anywhere to check the current users role before I load a view?
Any thoughts would be much appreciated!
Many thanks, James.
If this method works for you there is nothing wrong with it. Definitely if a whole page is blocked unless the user is an author then use filters. If it is just sections on the page there is nothing wrong with checking within the view.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community