Support the ongoing development of Laravel.io →
Database Eloquent

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?

Last updated 2 years ago.
0

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...

Last updated 2 years ago.
0

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

0

Thanks, Shineability, that helped... You would indeed expect the relationships to be loaded by default after attaching..

0

Thanks shineability that worked for me.

0

Sign in to participate in this thread!

Eventy

Your banner here too?

brucek2 brucek2 Joined 16 Mar 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.