Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

qace's avatar
Level 1

LDAP RECORD with Spatie Permissions gives error "The LDAP connection [mysql] does not exist."

I have been trying to fix this error for the last 2 days, and I have no clue how.

Summary: I have a function for deleting a department, in said function I want to also delete the roles and permissions associated with that department. This is the delete function:

public function delete(Department $department){




        // Get the permission associated with the department
        $permission = Permission::where('name', "modify_{$department->id}")->first();




        // Get the role associated with the department
        $role = Role::findByName($department->name);

        // Detach users from the role

        $defaultRole = Role::where('name', 'Default')->first();
        $users = User::role($role->name)->get();


        foreach ($users as $user) {
            $user->syncRoles([$defaultRole->name]);
        }

        // Detach the permission from the role
        $role->revokePermissionTo($permission);

        // Delete the role


        $role->delete();

        // Delete the permission
        $permission->delete();

        // Delete the department
        $department->delete();



        return redirect()->back()->with('message', 'Department and associated role/permission deleted successfully');



    }

The problem... it always stops when it reaches

$role->delete();

and gives error message: The LDAP connection [mysql] does not exist.

I disabled LDAP RECORD earlier and the code ran fine, but I do need the ldap. If anyone has experience with this, or can guide me in some direction, I will be grateful.

0 likes
6 replies
Bebec's avatar

Hi qace,

I encountered the exact same issue where the error message pops up whenever I try to perform a $role->delete(). I wasn't able to fix the problem - but I found a workaround. To do this, I simply wrote an extension model for the Role model that overrides the delete function.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Spatie\Permission\Models\Role;

class RoleExtend extends Role
{
    /**
     * Delete the role and detach all related permissions and users.
     *
     * @return bool|null
     * @throws \Exception
     */
    public function delete()
    {
        \DB::beginTransaction();

        try {
            \DB::table('model_has_roles')
                ->where('role_id', $this->id)
                ->delete();

            \DB::table('role_has_permissions')
                ->where('role_id', $this->id)
                ->delete();

            \DB::table('roles')
                ->where('id', $this->id)
                ->delete();

            \DB::commit();
    
        } catch (\Exception $e) {
            \DB::rollback();
            throw $e;
        }
    }
}

It's not the cleanest solution, but it buys me some time to deal with it later.

eislasq's avatar

I have a similar issue trying to get users attachet to a rol: $role->users()

  public function users(Role $role) {
        $users = $role->users()->paginate(10);
        return view('roles.users', compact('role', 'users'));
    }
aled2305's avatar

I have exact same issue, I get the same error when trying $role->users();.

Did any of you manage to find the root cause?

apogany's avatar

I just ran into this also.

spatie/laravel-permission tries to get the user model based on the apps auth settings in Spatie\Permission\Models\Role and Spatie\Permission\Models\Permission as well:

/**
 * A permission belongs to some users of the model associated with its guard.
 */
public function users(): BelongsToMany
{
    return $this->morphedByMany(
        getModelForGuard($this->attributes['guard_name'] ?? config('auth.defaults.guard')),
        'model',
        config('permission.table_names.model_has_permissions'),
        app(PermissionRegistrar::class)->pivotPermission,
        config('permission.column_names.model_morph_key')
    );
}

getModelForGuard() practically looks up the guards model:

function getModelForGuard(string $guard)
{
    return collect(config('auth.guards'))
        ->map(fn ($guard) => isset($guard['provider']) ? config("auth.providers.{$guard['provider']}.model") : null)
        ->get($guard);
}

Now, when you set up directorytree/ldaprecord-laravel, you set that to LdapRecords' User class thus later on every eloquent relation are going to fail trying to use the default connection name (usually 'mysql') which doesn't make sense in LdapRecords context.

// config/auth.php

'providers' => [
    // ...

    'users' => [
        'driver' => 'ldap',
        'model' => LdapRecord\Models\ActiveDirectory\User::class,
        'rules' => [],
        'scopes' => [],
        //...
    ],
],

The solution is to extend both the Role and Permission models' users() function, explicitly setting the related model to your User class:

namespace App\Models;

// ....

public function users(): BelongsToMany
{
    return $this->morphedByMany(
        User::class,
        'model',
        config('permission.table_names.model_has_roles'),
        app(PermissionRegistrar::class)->pivotRole,
        config('permission.column_names.model_morph_key')
    );
}
3 likes
Lurid's avatar

I use Laravel v10.10 and patie/laravel-permission v6.10

It helps me alot:

In "Models" folder create Role.php:

<?php

namespace App\Models;

use App\Models\User;
use Spatie\Permission\Models\Role as SpatieRole;
use Illuminate\Database\Eloquent\Relations\MorphToMany;

class Role extends SpatieRole
{
	public function users(): MorphToMany
	{
		return $this->morphedByMany(
			User::class,
			'model',
			config('permission.table_names.model_has_roles'),
			config('permission.column_names.role_id', 'role_id'),
			config('permission.column_names.model_id', 'model_id')
		);
	}
}

In "Models" folder create Permission.php:

<?php

namespace App\Models;

use App\Models\User;
use Spatie\Permission\Models\Permission as SpatiePermission;
use Illuminate\Database\Eloquent\Relations\MorphToMany;

class Permission extends SpatiePermission
{
	public function users(): MorphToMany
	{
		return $this->morphedByMany(
			User::class,
			'model',
			config('permission.table_names.model_has_permissions'),
			config('permission.column_names.permission_id', 'permission_id'),
			config('permission.column_names.model_id', 'model_id')
		);
	}
}

Usage: Replace all "use Spatie\Permission\Models\Role;" to:

use App\Models\Role;

and "use Spatie\Permission\Models\Permission;" to:

use App\Models\Permission;
1 like

Please or to participate in this conversation.