Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

341
Visualizações
How to show username from a relationship table in laravel

I have two tables users and tournaments. I have defined the relationships in the model for both as many to many. I have a third pivot table where user registered to tournament are stored. In this table i want to store the username of the user as well. Here is my storing function

$tournament->users()->syncWithoutDetaching([auth()->id()]);
$request->session()->flash('success', 'You have joined the tournament');
return back()->with('tournament', $tournament);

What can i add so i can store the username aswell? Thanks in advance

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

To Store User name In pivot table just create an extra column named user_name in pivot table and you can save it like below

 $userId = auth()->id();
 $userName =auth()->user()->name;

 $tournament->users()
            ->syncWithoutDetaching([$userId=>['user_name'=>$userName]]);
$request->session()->flash('success', 'You have joined the tournament');
return back()->with('tournament', $tournament);

To Fetch username as well when calling the relation add withPivot() to your Model

public function relationName(){
    return $this->belongsToMany(Model::class)->withPivot('user_name');
}

Update

 $userName =  auth()->user()->name ; // Instead name get the value you want from table column name

check the documentation

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda