feat(usermanagement): enhance user-branch relationship by syncing branches and adding timestamps

This commit is contained in:
Sholahuddin Al Ayubi
2025-12-12 11:08:36 +07:00
parent 0b28760f41
commit 8b51a4f039
3 changed files with 16 additions and 2 deletions

View File

@@ -217,11 +217,23 @@ class UsersController extends Controller
if ($validated) {
$user = User::create($validated);
if ($user) {
if ($request->roles) {
$user->assignRole($request->roles);
}
$branches = $request->input('branches', []);
$user->branches()->sync($branches);
if (!empty($branches)) {
$firstBranchId = $branches[0];
$user->branch_id = $firstBranchId;
$user->save();
}
return redirect()->route('users.index')->with('success', 'User created successfully.');
}
}

View File

@@ -110,6 +110,7 @@ class User extends Authenticatable
public function branches()
{
return $this->belongsToMany(Branch::class, 'user_branches', 'user_id', 'branch_id');
return $this->belongsToMany(Branch::class, 'user_branches', 'user_id', 'branch_id')
->withTimestamps();
}
}

View File

@@ -24,7 +24,8 @@ class UserBranch extends Model
public function user()
{
return $this->belongsTo(User::class);
return $this->belongsTo(User::class)
->withTimestamps();
}
public function branch()