kxh
kxh

Reputation: 59

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

Upvotes: 1

Views: 469

Answers (1)

JEJ
JEJ

Reputation: 904

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

Upvotes: 3

Related Questions