How to show username from a relationship table in laravel - php

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

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

Related

How to get all books from another table when using many to many relationship Laravel / Eloquent / Query builder

Let me explain the scenario.
i have tables:
competitions
id title body
then
books
id name user_id
then i have a pivot table to store participants
so
participants
id competition_id user_id
Now i have set some relationships for these models.
Competition model
public function participants()
{
return $this->belongsToMany('App\User');
}
User model
public function participatedCompetitions()
{
return $this->belongsToMany('App\Competition');
}
Now i am fetching one single competition and in that same query i need to fetch a list of books of the participants of that competition.
So how can i achieve this.
Thanks.
Here is how you get all the books:
$userIds = $competition->participant()->get()->pluck('id');
// $userIds is your collection of User Ids that is participant in that compititions.
$books = Book::whereIn('user_id',$userIds)->get();

Laravel one to one relationship. Save username from table to another table

TLDR: How do I create a relationship from one table to another? For example, I want changes from the user table automatically reflect on to the supplier table? Something like it's just referencing from the user table.
I have this 2 tables
========================
USER table
1. id
2. username
3. password
4. name
========================
and
========================
SUPPLIER table
1. id
2. username
3. name
========================
Every time I add a new user, it should automatically be saved into the supplier table. This is what I did:
function saveUser($postdata) {
$newUser= new \App\UserModel;
$newUser->email = $postdata['email'];
$newUser->password = $postdata['password'];
$newUser->name = $postdata['name'];
$newUser->save();
$this->saveSupplier($postdata['email'], $postdata['name']);
}
function saveSupplier($email, $name) {
$newSupplier = new \App\SupplierModel;
$newSupplier->email = $email;
$newSupplier->name = $name;
$newSupplier->save();
}
You see, it's not in a relationship right. It's just like manually saving into two tables. How do I make the Supplier table dependent on the user table? For example, everytime I make changes in the User table, it will automatically reflect on to suppliers table without having to fire an update method.
One way to achieve this would be to register and event in the boot method of your
User model.
protected static function boot()
{
parent::boot();
static::created(function($user) {
Supplier::create([
'username' => $user->username //or email or whatever you have.
'name' => $user->name
]);
});
}
Do you might be interested in triggers. If you can create triggers you can use them to insert into SUPPLIER every time you insert in USER.
Something like:
CREATE TRIGGER t_reflect_changes_user_supplier
AFTER INSERT
ON USER FOR EACH ROW
BEGIN
-- trigger code
INSERT INTO SUPPLIER (username,name) VALUES new.username,new.name
END;

check the database and insert if data not exist

I have the table 'role' with fields user_id and role_id.I have get the new value from the another query 154,516 from the for loop.I want to check 154 is in the role table user_id if not exit insert the new field or if exist update the field.In my case update the role_id for the user_id '154' and insert the new row for '516'.
role //table
user_id role_id
210 1
125 2
310 1
154 1
foreach($heads as $head){
$first_count=$first_count+1;
$roleMappingObject = new role_mapping();
$roleMappingObject->user_id = $head->user_id;
$roleMappingObject->role_id = 1;
$roleMappingObject->save (); //this will insert the new row for both 154 and 516 but I want to update '154'
}
In your case it seems like your role_id is not a foreign key, if that's the case you can just use the eloquent functions firstOrCreate/ firstOrNew
The firstOrCreate will search for instance with given data and return that instance or will save that instance.
The firstOrNew will find and return or create instance but doesn't save it in database as you will have to do it by calling save() method.
But if your role_id is foreign key i.e. key id of other table than you should prefer it in way defined in laravel's documentation for many to many relationship changing your role table to role_user and creating relation between users and roles table. In that way you will be able to use the methods attach / detach.
Set a many to many relation between your users and roles
User Model
public function roles()
{
return $this->belongsToMany(Role::class, 'role_user');
}
Role Model
public function users()
{
return $this->belongsToMany(Role::class, 'role_user');
}
And then
$user->roles()->attach($roleId));

How to find all id pivot from pivot table? (laravel 5.3)

I have a pivot table. The name is users_banks table. The table have field id, user_id, bank_id, status, account_name and account_number
Now, the pivot have 3 records
I display contain from pivot table using code like this :
$user_id = auth()->user()->id;
$user = $this->user_repository->find($user_id);
$account = array();
foreach($user->banks as $bank) {
$account[] = $bank;
}
dd($account);
The result display all record in the form of array. There exist value of field user_id, bank_id, status etc. But I don't find value of id
How can I find id from pivot table?
If the relationship is defined correctly you can use:
$bank->pivot->id
but make sure the user belongsToMany(Bank::class) and the bank belongsToMany(User::class) or else it wont work.

How to insert data into a pivot table with columns belonging to same model in Laravel?

I have a Block model which is basically for blocked users. It has a target_id and a sender_id, both of which are IDs from the users table. How can I add data to this pivot table when a user wants to block another user? What should my relationship methods look like?
Since both target_id and sender_id are fields from the users table, your relationship must be defined this way.
class User {
public function blocks() {
return $this->belongsToMany('App\User','blocked_users','sender_id','target_id')->withPivot(['id']);
}
public function blockedBy() {
return $this->belongsToMany('App\User','blocked_users','target_id','sender_id')->withPivot(['id']);
}
}
Here blocked_users is the name of the table.
So, to block a user you can do :-
//User who is going to block
$user = User::find($id);
$inputs = [$target_user_id];
$user->blocks()->attach($inputs);
//or you can use,
$user->blocks()->sync($inputs, false);
The false in the above sync is used when the old synced rows are ignored and new ones are attached.
To get the list of users who that particular user has blocked, you can do :-
$user = User::find($id);
$user->blocks;
And to get the list of users who that particular user is blocked by
$user = User::find($id);
$user->blockedBy;
Thanks,

Categories