Laravel - How to create user control in Laravel base role - laravel

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

Related

Laravel Releationship

I have one user table named "Users".
There are different roles (trainer and client).
I want to make like Trainer can have many clients, but client can have one trainer.
I made table in db like "ClientTrainer" where is stored only ID of users with columns
"id, client_id, trainer_id"
and I am trying to return something like this:
$user->allclients(); - return all clients (logged as trainer)
$user->owntrainer(); - return his trainer (logged as client)
Its fresh laravel 5.7 with only Auth and Roles.
I am sure it can only be done with modals, but i need a little help.
Thanks.
First, create a model for table ClientTrainer as well. Then try this inside your Users model:
public function clients()
{
return $this->belongsToMany(
"UsersModelNamespace",
"IntermediaryTableModelNamespace",
"trainer_id",
"client_id",
"id",
"id"
);
}
public function trainer() // will return a collection with one element
{
return $this->belongsToMany(
"UsersModelNamespace",
"IntermediaryTableModelNamespace",
"client_id",
"trainer_id",
"id",
"id"
);
}
Why I'm posting belongsToMany when retrieving the trainer? Laravel 5.7 does not support hasOneThrough() relationship.
The best thing you can do is to separate your Table into two; "users" & "trainers".
Even if they have exactly the same fields, they dont have the same functionality, so that justifies the separation. Then just add trainer_id in your table "users"

Laravel Auth::user relationship

In Laravel, i´m trying to show relation elements between Auth::user (Users) and Departments. In User table i have id, name, and department_id. In Departments table I have id and name.
In user model i create
public function department()
{
return $this->belongsTo('App\Models\Department');
}
Then, in blade template I try
Auth::user()->department
But return null and doesn´t show linked departments. Null is incorrect, all users have departments. Soo, ¿Any help? ¿What´s wrong in relation?
You can try this User::with('departmento')->find(Auth::id());
This method uses less queries - the others go after the user table twice:
auth()->user()->load(['department']);
You should add 'department_id' as a second parameter ($foreignKey) when calling belongsTo method, because it will searching for departmento_id by default.
public function departamento()
{
return $this->belongsTo('App\Models\Departamento', 'department_id');
}
Or just rename User::departamento() method to User::department()
public function department()
{
return $this->belongsTo('App\Models\Departamento');
}
Relation works with Model. Auth uses the session it not uses relation
Use User Model instead
optional(User::find(Auth::id())->departmento)->department_name

Eloquent relationship with 3 tables

I'm new to Stack Overflow and Laravel.
I try to develop a variable profilesystem in Laravel and I got 3 tables ('User', 'User_Fields', 'Fields').
The structure of the Fields table is following:
The structure of the user_fields table is following:
The User table is the standard table which came with Laravel 5
Now I want to get all fields from user_fields depending on which user is selected or logged in. If the user_field doesn't exists, the model should return null or create a new record for the user_field.
I tried a lot of "solutions" which came with eloquent like (hasManyThrough, belongsToMany) but I don't get the result I wanted.
Is there any solution with relationship methods?
Thanks for your help, and sorry for my bad english :/
You should be using the belongsToMany()->withPivot() to retrieve the intermediate table columns. Your user_fields is your pivot table so on your user model you should have:
class User extends Model
{
public function fields()
{
return $this->belongsToMany(Field::class, 'user_fields')->withPivot('value');
}
}
Then you can access your values for a user by:
$user = User::find($id);
foreach($user->fields as $field) {
$field->pivot->value;
}

How to check and get the result if the table contain user id in laravel

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.

Laravel user management

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.

Resources