Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

339
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!