I have some code that looks like this:
class User {
public function addRoleById($role_id) {
$this->roles()->attach($role_id);
}
}
// main() - does not work
$user = User::find(1);
$user->addRoleById(7); // succeeds, change now visible in database.
echo "Roles now include ". $user->roles; // new role is missing
// alternate main() -- does work
$user = User::find(1);
$user->addRoleById(7); // succeeds, change now visible in database.
$user = User::find(1) // reloads record I should already have and that has not changed?
echo "Roles now include ". $user->roles; // new role is present
To make this code work, I have to reload a database object immediately following an attach(), which I would not have intuitively expected. Am I doing something wrong in the first (non-working) case? Is there a more elegant workaround than reloading the object?
Was just looking for the same thing ;)
Try $this->load('roles') in your function after attaching the new role. This will refresh the roles relationship. Not sure if this is best practice, though, but it works...
It worked for me too, it would be great to know if load() makes another query to the database, I also think it should do that by default.
Thanks Shineability
Thanks, Shineability, that helped... You would indeed expect the relationships to be loaded by default after attaching..
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community