Reputation: 10044
I'm using a role package which stores hasMany relational data in my database. So there is a users
table and a user_roles
table with foreign keys...etc...
I am updating the model using the following code:
$user = User::findOrFail($id);
$user->update(request()->all());
$user->syncRoles(request()->input('roles', []));
Is there any way I can keep a reference of the roles
on the $user
variable so they can be used after these lines of code run?
I'm asking because I'm using a logging system after the fact like so:
activity()->on($user)->by(auth()->user())->withProperties([
'user' => $user,
'roles' => request()->input('roles'),
])->log('Updated User');
Which I would like to condense to just:
activity()->on($user)->by(auth()->user())->withProperties($user)->log('Updated User');
Upvotes: 1
Views: 1264
Reputation: 17388
You will need to refresh the model data from the database. E.g.
$user = $user->fresh('roles');
Upvotes: 3
Reputation: 11
Add the relationship in your User.php model :
public function roles(){
return $this->hasMany(Role::class);
}
Now simply call it in your code to get the roles like so:
$aUser = User::with('roles')->find($id);
$roles = $aUser->roles;
Upvotes: 0
Reputation: 45490
For example using lazy loading:
$user = User::findOrFail($id);
$roles = $user->roles;
and on your User
Model you would create a HasMany
relationship to roles table.
Eager loading:
$user = User::with('roles')->findOrFail($id);
Upvotes: 0