User ownership of table that can reference multiple users - laravel

I have a small application which has 2 migrations, team and team_user (it also has the default auth migrations).
The teams & default user migration has a belongsToMany relationship. As of now, everyone has the same relationship to each team. What would be a good elegant way to create ownership to the team as a sort of Team Leader. I'm currently exploring creating an additional team_leader migration but not sure if that's the correct solution.

If a team only has one lead you could add a team_lead_id column on the teams table that is a foreign key reference to the team lead user. Then you could define the relationship on the Team model:
public function leader()
{
return $this->belongsTo(User::class);
}
In the case of multiple leads per team then you'd need a pivot table like the team_leader table you mentioned.

Related

Laravel - Pivot table with 3 models realtionships Many to Many and One to Many

I want to make authentification in my Laravel project for Users who have Roles and Permissions. Actually That's not a problem to do but Users can create Teams or be invited member of any team and each User in any Team has his ONE Role in the team(in another team the user may have another role). In essense Users must have many Roles but only one role in one particular Team and I can't understand if I create correct DB relationships.
Please check the image with relationships to get more info:
In general:
Users have many Teams, and Teams have many Users(Many to Many)
Teams have many Roles, Roles have many Teams (Many to Many)
Users have many Roles, But only one Role in a Team what relationship should be there?
I'm interested how to do that properly. How to minimize messy code in the future and avoid of need to redesign DB relationships.
Thank you guys so much!
Maybe you do need a polymorphic relationship:
https://laravel.com/docs/master/eloquent-relationships#custom-polymorphic-types
with a morph map.
https://nicolaswidart.com/blog/laravel-52-morph-map

Many to many Laravel Eloquent relationship with multiple intermediate tables

I'm using Laravel 5.4 and have a model and table structure as follows:
users
-----
id
accounts
--------
id
holdings
--------
id
account_id (foreign key to account)
user_accounts
-------------
id
user_id
account_id
A user can have multiple accounts
An account can be shared by multiple users
Each account has multiple holdings
A user therefore indirectly has many holdings through their many accounts.
I need help to define a relation on the User model called "holdings" to get me all the holdings applicable to the user (based on the accounts they are linked to).
I've tried lots of different things and spent ages on google. I can get close with both belongsToMany and hasManyThrough, but they only seem to work for 3 table relationships where the intermediate table stores primary keys from the other tables. I can reduce my relationship to 3 tables (rather than 4) if I make use of the account_id foreign key on the holdings table to remove the need to join through the accounts table, however I can't seem to get this to work.
belongsToMany - holdings.id needs to be holdings.account_id:
select * from `holdings`
inner join `user_accounts` on `holdings`.`id` = `user_accounts`.`account_id`
where `user_accounts`.`user_id` = ?
hasManyThrough - user_accounts.id needs to be user_accounts.account_id:
select * from `holdings`
inner join `user_accounts` on `user_accounts`.`id` = `holdings`.`account_id`
where `user_accounts`.`user_id` = ?"
Well it's not strictly an answer as I was asking about laravel 5.4, but it is a possible solution.
It turns out I'm in luck as I came across this Laravel belongsToMany relationship defining local key on both tables which indicates the belongsToMany relationship has been enhanced in Laravel 5.5 to support this type of scenario.
I have upgraded my project to L5.5 and replaced my hack with the relation:
return $this->belongsToMany(Holding::class, 'user_accounts', 'user_id', 'account_id', null, 'account_id');
And am happy to say it seems to work perfectly - at least for basic gets which is my use case, I haven't tried any updates etc.
Thanks to #cyberfly and those who posted the answer above

Laravel: Table structure for multiple users types, polymorphic relationships

In my site (api using laravel 5.6 and laravel passport) I have two types of users (Teachers and Students), in the future there will be more. The teacher and student entities are very different, meaning that if I keep them all in one table, the table will be long and many fields will have a null value. Right now I have one Users table with common fields and two other tables (Teachers and Students) to which I have setup a polymorphic relationship from user. My question is if this is a good approach, or if there are other ways to handle this more elegantly?
I would create 1 table for Teachers and 1 table for Students and not use the Users table/model. This way you can keep them completely separate and not worry about adding more types of users in the future. Continually trying to fit new users into your existing Users model, which would be shared, is a headache. I made this same mistake when I started and eventually had to rework the project.
There are plenty of guides for Laravel multi-auth / multi-user online.
Here are a couple to help you get started:
https://medium.com/hello-laravel/multiple-authentication-system-laravel-5-4-ac94c759638a
https://www.codementor.io/okoroaforchukwuemeka/9-tips-to-set-up-multiple-authentication-in-laravel-ak3gtwjvt
Also, there are cases where it makes sense to use the User model for multiple types of users. For example, you may have multiple roles for a user where most/all of the fields are the same (not your scenario). In this case, you can assign a 'role' to each User and the check the roles for actions (e.g. add middleware to prevent roles from accessing various routes). Here is an example:
https://medium.com/#ezp127/laravel-5-4-native-user-authentication-role-authorization-3dbae4049c8a
Since you said the teacher and student entities are very different, you should keep them separate.

Laravel Relationships and Pivot

I have a users table
id
role_id
"other standard auth stuff"
I also have a roles table
id
role
I do not want to change the users table in the sense that its currently doing all the auth stuff provided with laravel 5.4 but
I have users with a role. Let's say coach and player are 2 types of roles and I need to now allow coaches to add players and players to add themselves to coaches and have them related.
Is it possible to relate the User model role type coach and role type player in a separate table like coaches_players without creating new models for Player and Coach? If so can someone point me in the right direction. I know if I were to start from scratch I would have Player and Coach related through belongsToMany etc. but everything in my system works off of user_id and I do not want to change all the Auth functionality etc.
Is there a way to create those Player and Coach models that extend User and create the relationships through those?
Is there a way to relate 2 columns in the User table through a pivot table coaches_players?
Just looking for some guidance and possibly some links if you have them off the top of your head.
Sure, you can do this. Just create coaches_players table and define new relationships in User model:
public function players()
{
$this->belongsToMany(User::class, 'coaches_players', 'coach_id', 'player_id');
}
public function coaches()
{
$this->belongsToMany(User::class, 'coaches_players', 'player_id', 'coach_id');
}

Three way relationship in Laravel

having a brain failure with a relationship between three objects, hoping someone can help me out.
I have four models: Team, User, ProjectType and Project
Team has many User, has many ProjectType
User belongs to many Team, has many ProjectType
ProjectType belongs to manyUser, belongs to many Team, has many Project
Project belongs to ProjectType
As a single user can belong to many teams, I want to request the ProjectTypes that a User has access to, but only within the Team they are currently logged in with. It may be the case that a User has access to project types across multiple teams, but will only be logged in to one team at any time, so I need just that subset.
I'm hoping this structure makes sense, but I'm struggling to get access to the data I want easily
So I'd like to do $user->projectTypes and get all project types for that user, but only the subset of the team they're currently logged in with.
Equally, once I've got that, I want to be able to get $user->projectTypes->projects within that set.
I'd like to do this whilst maintaining all of the nice relationship methods I get with Laravel, but am struggling to setup the data structure to support this, and get the data in turn.
Worth adding I'm using Laravel 4.2, but am not desparately tied to it, and can upgrade to 5.x if necessary to get this functionality.
Once you've defined the relationships as you've described, you can access the ProjectTypes that belong to a User, that also belong to a certain Team (in your case $teamid should be the id of the Team that the User is currently logged in to) like so:
$projectTypes = $user->projectTypes()->where('team_id', $teamid)->get();
To easily access a collection of all Projects that belong to all ProjectTypes that belong to a User, you would first define the HasManyThrough relationship like so:
class User extends Eloquent {
public function projects()
{
return $this->hasManyThrough('Project', 'ProjectType');
}
}
Then you can access that collection like so:
$projects = $user->projects;
And finally, to access the Projects that belong to the ProjectTypes that belong to a User, that also belong to a certain Team (i.e. what it seems you're looking for), you can use lists() to get a list of relevant ProjectType ids, then whereIn() to filter for those within that list:
$projectTypeIds = $user->projectTypes()->where('team_id', $teamid)->lists('id');
$projects = $user->projects()->whereIn('projecttype_id', $projectTypeIds)->get();

Resources