Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
Invalid Model instance added to relations in this model error when updating roles on a user
  • I wrote a simple ormauth driver.  I've associated roles to groups so depending on what group a user is in they get a choice of roles to choose from.

    I've got a simple form to change user details and if I change the group_id then select roles and click save get the following exception error :

        Fuel\Core\FuelException [ Error ]:
        Invalid Model instance added to relations in this model.
        PKGPATH/orm/classes/manymany.php @ line 252

    I assign roles like this :

        $user = \Auth\Model\Auth_User::find_by_id($user_id);
        if(count($roles) != 0)
            foreach($roles as $role_id)
                $user->roles[$role_id] = \Auth\Model\Auth_Role::find((int)$role_id);
            $updated_roles = $user->save();
            return $updated_roles;
        } else {
            return 0;

    I get the same error if I use the \Auth::update_user() method.

    If I simply change the group_id but don't select any roles, the save works fine but to change roles I have to submit the form to change the group_id, then go back into the edit view and change the roles.

    What am I doing wrong here?
  • HarroHarro
    Accepted Answer
    Auth classes are aliased to global, and that is true for the models too (otherwise you can't extend them).

    This means you should use


    and not


    Because you do this, The ORM complains that you have assigned a model instance in

    $user->roles[$role_id] = \Auth\Model\Auth_Role::find((int)$role_id);

    that doesn't match the defined class for that relation.
  • I've amended the function to \Model\Auth_Role but still getting the same result.

    I can understand how ORM would struggle with \Auth\Model but surely this would happen all the time.  I'm finding that it will work if I reload the edit view after saving the group_id change but if I change the group and role in the same form submit then it throws the error.
  • Scratch that previous comment.  Although changing \Model\Auth_Role didn't seem to initially to fix the issue.  What I found on further investigation was the javascript behind the role_id form select was setting the option values to the array numerical index of the returned json object, not the actual role_id.  So ORM must have been failing to find an association with role_id = 0.

    Learned some more good stuff today

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion