Laravel Releationship - laravel

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"

Related

Laravel: sync many to many on a subset of rows

There is a multi-tenant laravel application that is implemented in a single database. There are models User and Role with the following relation in User model:
public function roles(): BelongsToMany
{
$relation = $this->belongsToMany(Roles::class, 'role_users', 'user_id', 'role_id')->withTimestamps()->withPivot('tenant_id');
$relation = $relation->where(function ($query) {
$query->where('tenant_id', Tenant::current()->id);
});
return $relation;
}
The role_users table contains user_id, role_id, tenant_id. A user may present in multiple tenants, when I update roles of a user in a tenant, I need to only update the roles of the current tenant, not the user roles on all tenants. This the code I write :
$user->roles()->syncWithPivotValues($roles, ['tenant_id' => Tenant::current()->id]);
But it doesn't work and syncs all roles not the roles of the current tenant. How can I solve the problem?
You can use the wherePivot() method passing the tenant id.
You can find the documentation here: https://laravel.com/docs/9.x/eloquent-relationships#filtering-queries-via-intermediate-table-columns
The code should then look like this:
$user->roles()->wherePivot('tenant_id', Tenant::current()->id)->sync($roles);

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;
}

Eloquent relationship for multiple table

I am working in laravel5.4. I have created four table as ticket, users, and company. Here, I have stored users id in ticket table. And stored company id in users table.
Here, I want to show ticket's user name with that users company name.
Here, I have create relation for it that looks like below.
Ticket model :
public function requesters(){
return $this->belongsTo('App\User','requester_id');
}
Here requester_id is who create ticket.
Users model :
public function company()
{
return $this->belongsTo('App\Models\Admin\Company');
}
Company model :
public function Users()
{
return $this->hasOne('App\Users');
}
Here, I have written query to get users information that looks like below.
Ticket::with('requesters')->orderBy('subject','asc')->paginate(10);
Now, I want to fetch company information or request_id So what changes should I have to do in this query to fetch company info along with ticket and users ?
If you want to to Eager load multiple relationship you can put them all in single with like this:
Ticket::with('requesters','requesters.company')->orderBy('subject','asc')->paginate(10);
but if you load nested relationship you can use shorter notation - you can omit parent relationship, so it's enough to use here:
Ticket::with('requesters.company')->orderBy('subject','asc')->paginate(10);
Try this, it should work for this case:
Ticket::with('requesters')
->with('requesters.company')
->orderBy('subject','asc')->paginate(10);

Laravel - How to create user control in Laravel base role

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

Resources