I have a Many To Many relationshp between User Model & Wallet Model.
So at the User.php Model:
public function wallets() { return $this->belongsToMany(Wallet::class,'user_wallet','user_id','wallet_id')->withPivot('balance'); }
And at Wallet.php Model:
public function users() { return $this->belongsToMany(User::class,'user_wallet','wallet_id','user_id'); }
And also the table Migration of user_wallet
table also goes here:
public function up() { Schema::create('user_wallet', function (Blueprint $table) { $table->bigIncrements('id'); $table->unsignedBigInteger('user_id'); $table->foreign('user_id')->references('usr_id')->on('users'); $table->unsignedBigInteger('wallet_id'); $table->foreign('wallet_id')->references('id')->on('wallets'); $table->integer('balance'); $table->timestamps(); }); }
And at the Controller, I added this:
$bal = Wallet::with("users")->whereHas('users',function ($query)use($wallet_id,$user_id){ $query->where('wallet_id',$wallet_id); $query->where('user_id',$user_id); }); dd($bal);
But now I need to update balance
filed of this pivot table which has the same user_id
and wallet_id
:
So how to do this?
I would really appreciate any idea or suggestion from you guys…
Thanks in advance.
Advertisement
Answer
use updateExistingPivot
$wallet = Wallet::find($wallet_id); $wallet->users()->updateExistingPivot($user_id,["balance"=>500]);
Ref:https://laravel.com/docs/8.x/eloquent-relationships#updating-a-record-on-the-intermediate-table