Search code examples
phplaravellaravel-5.3entrust

Zizaco/entrust Saving permission uses roles table


I am using the dependency of Zizaco/entrust for creating roles and their permissions in my webapplication, which is build in laravel 5.3. The problem I am having is (as the title says) whenever I try to save a newly created Permission. It is stored in the roles table.

The migration file hasn't been changed from the original zizaco/entrust package. I used the php artisan vendor:publish to create the migration. The models of Role and Permission is quite like the documentation says:

namespace App\Models;

use Zizaco\Entrust\EntrustRole;

class Role extends EntrustRole
{

protected $table = 'roles';

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
  protected $fillable = [
      'name', 'display_name', 'description',
  ];
}

And the permission

namespace App\Models;

use Zizaco\Entrust\EntrustRole;

class Permission extends EntrustRole
{

protected $table = 'permissions';

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
      'name', 'display_name', 'description',
  ];
}

and in the seeder file, i use the following code to generate role and seeder:

use App\Models\Permission;
use App\Models\Role;
use Illuminate\Database\Seeder;

class RoleSeeder extends Seeder
{
/**
 * Run the database seeds.
 *
 * @return void
 */
public function run()
{
    $owner = new Role();
    $owner->name         = 'owner';
    $owner->display_name = 'Eigenaar';
    $owner->save();

    $createOwner = new Permission();
    $createOwner->name         = 'create-owner';
    $createOwner->display_name = 'Eigenaar toevoegen';
    $createOwner->save();
 }

The config file of entrust is also modified to the correct path of Role and Permission Model and the tables aswell.

I have tried composer dump-autoload and even php artisan cache:clear.

Is there something that i missed? please help. Please pardon my english if it isn't grammatically correct.

EDIT: when i try to attach my permission to the role by the following line:

$owner->attachPermission($createOwner);

I get a sql error:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fail s (reunions_dev.permission_role, CONSTRAINT permission_role_permission_id_foreign FOREIGN KEY (permission_id) REFERENCES permissions (id) ON DELETE CASCADE ON UPDATE CASCADE)

that is because there is no record of Permission to link the ID to. kinda obvious.


Solution

  • The problem I am having is (as the title says) whenever I try to save a newly created Permission. It is stored in the roles table.

    Looking at the code you've provided, you extended the wrong class for your Permission model. Change the use statement & extending class in your Permission model to EntrustPermission:

    use Zizaco\Entrust\EntrustPermission;
    
    class Permission extends EntrustPermission