diff --git a/app/Http/Controllers/UsersController.php b/app/Http/Controllers/UsersController.php index cefa3f3..d4f3fa7 100644 --- a/app/Http/Controllers/UsersController.php +++ b/app/Http/Controllers/UsersController.php @@ -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.'); } } diff --git a/app/Models/User.php b/app/Models/User.php index a872078..81e5eb3 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -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(); } } diff --git a/app/Models/UserBranch.php b/app/Models/UserBranch.php index 0bf2045..3836a06 100644 --- a/app/Models/UserBranch.php +++ b/app/Models/UserBranch.php @@ -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()