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

Time:08-26

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;
   }

CodePudding user response:

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();
    }
}
  • Related