Laravel ORM relationship - manager-employee over the same table of users - laravel

I have a user_managers pivot table that gets both keys from the users table:
employer_user_id
employee_user_id
I believe users would have a many to many relationship as a user can be managed by more than 1 manager there will be users who manage 1 or more users, while other users (excluding those under them) would manage them while there will be users who don't manage at all and a User can have only 1 manager.
My first try at defining this was to build another model named Manager representing the user_managers pivot table, so in User model I wrote the following 2 functions:
public function managedBy()
{
return $this->belongsToMany('Manager', 'employer_user_id');
}
public function manages()
{
return $this->hasMany('Manager', 'employee_user_id', 'employer_user_id');
}
Does this make sense or do you know of a better way to implement this kind of structure?

If a user can have only 1 manager then you can define you relationship as one to many like
//User model
public function managedBy()
{
return $this->belongsTo(User::class, 'manager_id');
}
public function managees()
{
return $this->hasMany(User::class, 'manager_id');
}
you don't need to pass $id to your relationship definition.
For multiple managers, Yes you would need a many to many relationship by adding a junction/pivot table which i guess you already have user_managers, Now you need to define your relationships using belongsToMany for managers and mangees like
public function managers()
{
$this->belongsToMany(User::class, 'user_managers', 'employer_user_id')
}
public function managees()
{
$this->belongsToMany(User::class, 'user_managers', 'employee_user_id')
}

Related

Laravel Create multiple records in Pivot table

I'm trying to create a function in our Laravel 5.8 app that would add multiple records to a pivot table. At present we have the following setup;
Users
Training Courses
Users Training Courses (pivot table for the above relationships, with a few extra fields)
I want to be able to show all users in the database, then check their name, pick a training course and hit "Add" and it'll create a record in the pivot table for each user that was selected.
I can't figure out where to start with this - it seems like I need to have a "for each user selected, run the store function" loop in the controller, but I have no idea where to start.
I wasn't sure if there was an easy way to do this in eloquent or not. Is there a simple way to do this?
Eloquent does this automatically if you set up the relationships correctly and you don't have to worry about pivot tables.
class Users
{
public function trainingCourses()
{
return $this->hasMany(TrainingCourses::class);
}
}
class TrainingCourses
{
public function user()
{
return $this->belongsTo(User::class);
}
}
Then you can use the save() method to create the relationship. But I find it better to wrap this function inside a helper method that you can use throughout your code:
class Users
{
...
public function assignTrainingCourse(TrainingCourse $trainingCourse)
{
return $this->trainingCourses()->save($trainingCourse);
}
}
In your code, you could then do something as simple as this:
$user = User::find(1);
$trainingCourse = TrainingCourse::find(1);
$user->assignTrainingCourse($trainingCourse);
Building on this, suppose you have the following route to assign a training course, where it expects a trainingcourse_id in the request:
Route::post('/users/{user}/trainingcourses', 'UserTrainingCoursesController#store');
Thanks to route model binding, Laravel can inference the parent model (user) from the URL, and your controller might look like this:
// UserTrainingCoursesController.php
public function store(User $user)
{
$trainingCourse = TrainingCourse::find(request()->input('trainingcourse_id'));
$user->assignTrainingCourse($trainingCourse);
return back();
}
Of course, you'll want to put some validation in here, but this should get you started.

How to add multiple users with same login page, but differentiating roles

I want to put all my different users (teachers, students, admins) in the same table but how can I differentiate between them.
When I add the relationships in this table, for example : the teachers belongs to a departement table:
public function departement()
{
return $this->belongsTo(Departement::class);
}
And the students belongs to another table which is faculty table:
public function faculty()
{
return $this->belongsTo(Faculty::class);
}
The problem is when I add those relationships to the users table it will add automatically to all types of users (teachers, students, admins...).
use where
public function departement()
{
return $this->belongsTo(Departement::class)->where('users.type','=','student');
}
public function faculty()
{
return $this->belongsTo(Faculty::class)->where('users.type','=','admin');
}

A model with polymolymorphic ony to many and simple one to many relationship

I am using laravel 5.7. I have now a situation where i have a Fight model with structure user_id, fightable_id
i have two other tables users and monsters. so users_id refers to users (a user can have many fights) and fightable_id can refer to either a user or a monster (monsters table). so I have to define the functions for the relation ship
for User model i have to do
1.for polymorphic one to many relationship
public function fights()
{
return $this->morphMany('App\Fight', 'fightable');
}
2.for simple one to many relationship
public function fights()
{
return $this->hasMany('App\Fight');
}
I am confused now. ofcourse the only way is to change the functions name. but i will be doing the correct thing by changing the function names right (as both the functions have same name). or is there anything I am doing wrong?
I'm not sure I understand your question completely but I'll try my best!
Also this post will really help you understand the problem you are facing I think,
Laravel morph relationship
Using the code from the post I linked but taking your tables would produce models defined like this.
User Model
class User extends Model
{
public function fights()
{
return $this->hasMany('App\Fight');
}
}
Fight Model
class Fight extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
public function fightable()
{
return $this->morphTo();
}
}
Monster Model
class Monster extends Model
{
public function fight()
{
return $this->morphOne('App\Fight', 'fightable');
}
}
If you still feel this has not answered your question or need some more help just let me know!

franchise/branch relations with user laravel

i am unable to find best suited relations for creating a courier website.
my requirements are
a branch can have many users
a franchise can be associated with only one user
a branch can have many franchise
branch user can access through franchise models
Note:- branch and franchise have different profiles
I want to avoid directly jumping to the answer and convert the statements you have given into more easier relationship descriptions :
- 1 branch has many franchises
- 1 user has 1 franchise
This will then help you to understand :
- branch <> franchises is one to many relationship
- franchise <> user is one to one relationship
Models :
Branch Model :
public function franchises()
{
return $this->hasMany(Franchise::class);
}
Franchise Model :
public function branch()
{
return $this->belongsTo(Branch::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
User Model :
public function franchise()
{
return $this->hasOne(User::class);
}
To make these relationships work, you need to have proper foreign keys in your database schema. To know more please check documentation

Access Method in a hasManyThorugh

I have 4 tables,
props, listing, offers, contact
props has many listing, listing belongs to props
public function listings()
{
return $this->hasMany('App\Models\Listing\Listing');
}
offer belongs to listing,
public function property()
{
return $this->belongsTo('App\Models\Property\Property')->with('owners');
}
then
offer belongsToMany contact trough offer_contact table
public function buyers()
{
return $this->belongsToMany(Contact::class, 'offer_contact', 'offer_id', 'contact_id')->with('primary_email');
}
My question is, how to access buyers()?
Something like $props->buyers()
In props model, what I did is
return $this->hasManyThrough('App\Models\Offer\Offer', 'App\Models\Listing\Listing');
You cannot. You may use nested iterations to get properties, listings belongs to each property, offers belongs to each listing and then customers belonging with the offer.
Alternatively, you may use the raw query to get the desired result using DB::statement();
I created a HasManyThrough relationship with unlimited levels: Repository on GitHub
After the installation, you can use it like this:
class Property extends Model {
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
public function buyers() {
return $this->hasManyDeep(Contact::class, [Listing::class, Offer::class, 'offer_contact']);
}
}

Resources