Im running Laravel 4 for my app ... Im a newbie.
I have created a small little application using the standard built in authentication and everything is working fine.
I have the User.php model and the routes file taking care of all my requests.
What i want to do, is add administrators, i have added a field in my users table which is named 'is_admin' .. its an integer of 1 or 0.
What i want to be able to do is something like the following
if is_admin() {
// Do stuff here if im an admin
}
Can anyone help me out with how i can achieve that .. All i have at the moment is a database column.
Cheers,
Actually you may check if the user is an admin ot not using this:
if(Auth::user()->is_admin) {
//...
}
Because Auth::user() returns the currently logged in user and is_admin field is available in the users table so if a user is logged in then you may simply check by checking the Auth::user()->is_admin property of the logged in user model. If a user is admin then the value is 1 and this will be true and for 0 result will be false in the if condition.
If you want to add a method in the user model then you may try this way:
public function isAdmin()
{
return $this->is_admin;
}
So you may check like:
$user = User::find(1);
if($user->isAdmin()) {
//...
}
$val = (bool)DB::table(DB::raw('DUAL'))->whereExists(function($query) use ($userId)) {
$query->from = 'users';
$query->where('id', $userId)->where('is_admin', 1)->select(DB::raw(1));
})->first([DB::raw(1)]);
This will run a SELECT 1 FROM DUAL WHERE EXISTS (SELECT 1 FROM users WHERE id = X and is_admin = 1 query which will return a boolean if the row exists or not.
DUAL is a dummy table in MySQL and used so we don't have to go trough a table. DB::raw(1) is used as we don't need to fetch column data for this, we just want true/false.
If you're already logged and you're using Laravels Auth you can just do as #WereWolf mentioned.
Related
I am new with Laravel and i am trying to build an application based on roles, but in my case the user can have only one role (there is no a pivot table between users and roles) and we can create new role us we like(assign many permissions to one role). Any help? and thanks a lot
So here is one way I would do it.
You need 2 tables :
One table I would call "ranks", inside it you can have everything about the rank itself :
Its id of course, but also :
Is it an admin rank ? (all permissions)
What's it name ? ...
One table I would call "ranks_abilities", inside it you can have everything about what a rank can do
Therefore, it would have three columns : an id, a rank_id, and the name of the ability
And you need to put the rank_id inside the users table.
Note : if you wanna do it really nicely, you can have a table "abilities" containing all the possible abilities, and you'd reference their ids instead of the name
So how would it work ?
You would therefore have three models :
User
Rank
RanksAbility
Inside of your User model, you'd have a belongs_to relationship to the Rank model (call it rank)
Inside of the Rank model, you'd have a has_many relationship to the RanksAbility model (call it ranks_abilities)
I guess we are now fine with the database structure, let's get to the point of allowing to do something.
So, of course, where a login is required, you have the auth middleware that does it perfectly
Then, to handle the permissions itself, there are several ways to do it, here is one I would recommend.
Step 1 :
Create a policy for some action for example if you have posts you can create a PostPolicy (https://laravel.com/docs/5.4/authorization#creating-policies)
If, you want, for example, a permission so that a user can edit all posts, you'd have an update method in that PostPolicy
public function update(User $user, Post $post)
{
return $user->hasPermission('post.update'); // You can also add other permissions for example if the post belongs to your user I'd add || $post->user_id == $user->id
}
I would do something like that.
Then, you'd have to make the hasPermission method.
So, in your User model, you could put something like this :
public function hasPermission($permission){
if(!$this->relationLoaded('rank')){
$this->load('rank', 'rank.ranks_abilities');
}
if(!$this->rank){
return false;// If the user has no rank, return false
}
foreach($this->rank->rank_abilities as $ability){
if($permission === $ability->name){
return true;// If the user has the permission
}
}
return false;
}
And here the method is done.
Last step, you can use all the methods listed here https://laravel.com/docs/5.4/authorization#authorizing-actions-using-policies to avoid an user from doing something he can't.
Personally, I would do a FormRequest, and handle the authorization with it (https://laravel.com/docs/5.4/validation#authorizing-form-requests).
I hope to be clear, if you have any more questions go ahead
For setting up customized user roles and permissions, you may give a try to https://thewebtier.com/laravel/understanding-roles-permissions-laravel/.
It's a complete guide on how to setup roles and permissions in your Laravel project.
Hello I'm a newbie with Laravel, I wanna ask how to make user control in Laravel base user role,
I have 5 table
table menus
table user_menus
table roles
table user_roles
table users
and then I want to validate which user can access the menu
the example role_id 1 (administrator) can access menu 1 and 2 ('master maintenance' and 'user')
and if authentication then can access the module, if not then redirect to 404.
Please help me! I have no idea what should I do :(
I looking for many sites but I don't get any solution
Thanks for answer
I not sure because i don't have your database but i think you and set relation in you model for make it easy
in model UserRole add relation
public function usermenus()
{
return $this->hasMany('UserMenus', 'role_id', 'role_id');
}
in model UserMenus add relation
public function menus()
{
return $this->hasOne('Menus', 'menu_id', 'menu_id');
}
when you want to query data
$menus = UserRole::where('user_id', $userId)->with('usermenus.menus')->get()->toArray();
print_r($menus); exit;
//or use dd($menus); for print and die
I have create a relationship between user and table column, I want show the table list which is belongs to particular user. For example if user_id 1 is logged in the system, the system will only show the information belong to him which is Table 1.
This is my controller code :
public function show(Request $request){
$user_id=Auth::user()->id;
$table= Roundtable::findOrFail($user_id);
return view('users.tables.show')->withTables($table);
}
I know that $table= Roundtable::findOrFail($user_id); is incorrect but I had no idea how to do because I am new for laravel.
If user has just one table and if Roundtable model has user_id you can use this query:
Roundtable::where('user_id', $id)->first();
It will give you user's table or null if table doesn't exist.
Another way to get table is to use relation:
auth()->user()->roundTable;
Well i found the solution, just need to change the code into
$id=Auth::user()->id;
$table= Roundtable::where('user_id',$id)->get();
return view('users.tables.show')->withTables($table);
then the result will return correctly.
i'm using CodeIgniter 3 with Community Auth for Authentication. I want to restrict the database result based on the role.
Right now in the model the functions are like this:
get_finantial_report( some parameters, user_level, user_id)
and i get the user_level and user_id in the controller:
$this->auth_role
$this->auth_user_id
Would be better to remove those parameters (user_level, user_id) from the function and get them inside the funcion instead of passing them from controller to model?
You can catch those variables in controller and do your validations on them and then send them to model for db stuff.
Example:
For this there are two logic in my mind right now:
1- On base of user_level decide in controller whether you want to bring the result for this user or not.
e.g
if($user_level == 'something')
{
$result = $this->model_name->get_finantial_report(some parameters, user_id);
}
2- Or after you have sent the user_role to the model there make a check on role whether you want to return the result or not.
function model_function(some parameters, user_level, user_id)
{
if($user_level == 'something')
{
return $result = $this->db->query("// anything");
}
}
In Laravel we can manage Users and Permissions easly but i've a problem with my application.
In my application a User is attached to One or Many department.
But a User can have different Role/Permission between departments. That is the problem. In the department One he can have a Admin Role and in the department Two he can only have a User Role. When the User switch between department i would like that his Role can be update.
How i can manage this in Laravel and Eloquent ?
Thank you for your help.
Jeffrey
Without seeing any of your code, I am forced to be fairly generic here. But here is the basic concept.
Architecture
Assuming you have tables like departments, users, roles, and permissions already, all you would need next is define a joining table. Something like this:
department_role_user
department_id // for this department
role_id // this role is assigned to
user_id // this user
Authorization
Define something like a hasPermissionTo() method on your User model.
Definition
class User
{
public function hasPermissionTo($action, $department)
{
// first get permission
$permission = Permission::where('action', $action)->first();
// get all roles which have this permission
$roles = $permission->roles;
return DB::table('department_role_user')
->where('user_id', $this->id) // current user
->where('department_id', $department->id) // the dept
->whereIn('role_id', $roles->pluck('id')) // any of the roles
->exists();
}
}
Usage
And use it like so.
if ($user->hasPermissionTo('do-something', $someDept)) {
// allow action
} else {
// no way
}
This should also work nicely with Laravel's Gates and Policies. Just use your new hasPermissionTo() method inside your gate/policy definitions.