Error encoding model [App\Models\RoleHasPermission] with ID [] to JSON: Recursion detected

Issue

I’m getting an error when storing a permission assigned for a role. The error shows on the line $permission->save();
I don’t know how to resolve this issue. need some help.
thanks in advance

here’s my controller

 public function storePermission(Request $request, $id)
{
    $permissions = $request->permissions;
     RoleHasPermission::where('fkrole_id', $id)->delete();
     foreach($permissions as $permission)
     {
        $permission = new RoleHasPermission;
        $permission->fkrole_id = $id;
        $permission->fkpermission_id = $permission;
        $permission->save();
     }

here’s my model

    class RoleHasPermission extends Model
   {
    use HasFactory;
    protected $table = "role_has_permissions";
    public $fillable = ['fkrole_id','fkpermission_id'];
    public $timestamps =false;
   }

Solution

You are overwriting the $permission variable which you are trying to use as as property with the new RoleHasPermission

Try using a different names

public function storePermission(Request $request, $id)
{
    $permissions = $request->permissions;
    RoleHasPermission::where('fkrole_id', $id)->delete();
    foreach($permissions as $permission)
    {
        $roleHasPermission = new RoleHasPermission;
        $roleHasPermission->fkrole_id = $id;
        $roleHasPermission->fkpermission_id = $permission;
        $roleHasPermission->save();
    }
}

Answered By – John Zwarthoed

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published