My form to add data is like this :
When klik save, It will call controller
My controller is like this :
public function store(Request $request)
{
$param = $request->only('account_name','account_number','bank_id','branch');
$result = $this->user_service->addUserBank($param);
if($result)
$status='success';
else
$status = 'failed';
return redirect('member/profile/setting/account')->with('status',$status);
}
My service is like this :
public function addUserBank($param)
{
$instance = User::where('id', '=', auth()->user()->id)->first();
$param['user_id'] = auth()->user()->id;
$param['status'] = 0;
$instance->banks()->attach([
'status' => $param['status'],
'account_name' => $param['account_name'],
'account_number' => $param['account_number'],
'branch' => $param['branch']
]);
return $result;
}
My model user is like this :
<?php
namespace App;
use App\Models\MasterData;
use Collective\Html\Eloquent\FormAccessible;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable, FormAccessible;
protected $fillable = [
'name', 'email', 'password', 'api_token','birth_date','mobile_number','gender','full_name'
];
protected $hidden = [
'password', 'remember_token',
];
public function banks()
{
return $this->belongsToMany(MasterData::class, 'users_banks', 'user_id', 'bank_id') ->withPivot('status','account_name','account_number','branch')->withTimestamps();
}
}
So I have 3 table : users table, users_banks table (pivot table), and master_datas table
List of the names of the banks located in the master_datas table with type bank
Users table have field id, name, email, password etc => See model user
Master_datas table have field id (this is bank id), name (this is bank name), type (there exist type of bank, order status etc. So, get type = bank)
Users_banks table have field id, user_id, bank_id, status, account_name, account_number, branch
When run, it does not successfully insert into the pivot table (table users_banks).
It looks like my way to insert into the pivot table, not true.
Can you help me?
Additional
Table Master_datas is like this :