To automatically set the sport_club_id and sport_league_id on the TeamMember model when saving it through the LeagueTeam model, you can use Eloquent model events or override the save method in the TeamMember model. Here's a solution using model events:
-
Using Model Events:
You can listen to the
creatingevent of theTeamMembermodel to set the additional attributes before the model is saved to the database.First, ensure you have the necessary relationships defined in your models:
// LeagueTeam model public function teamMembers() { return $this->hasMany(TeamMember::class); } // TeamMember model public function leagueTeam() { return $this->belongsTo(LeagueTeam::class); }Then, in the
TeamMembermodel, you can set up the event listener:use Illuminate\Database\Eloquent\Model; class TeamMember extends Model { protected static function boot() { parent::boot(); static::creating(function ($teamMember) { if ($teamMember->leagueTeam) { $teamMember->sport_club_id = $teamMember->leagueTeam->sport_club_id; $teamMember->sport_league_id = $teamMember->leagueTeam->sport_league_id; } }); } } -
Using the
saveMethod Override:Alternatively, you can override the
savemethod in theTeamMembermodel to set these attributes before saving:use Illuminate\Database\Eloquent\Model; class TeamMember extends Model { public function save(array $options = []) { if ($this->leagueTeam) { $this->sport_club_id = $this->leagueTeam->sport_club_id; $this->sport_league_id = $this->leagueTeam->sport_league_id; } return parent::save($options); } }
With either approach, when you call $league_team->teamMembers()->save($team_member);, the sport_club_id and sport_league_id will be automatically set based on the LeagueTeam model.