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

Ranjeet's avatar

How to use Zizaco/entrust Package to Create User Role

Hello everybody i am new to laravel and i want to use Zizaco/entrust(https://github.com/Zizaco/entrust) package to create multiple roles. I have already install it but confuse about the tables it made in database. i want to know relation between "roles","roles_user","permissions","permission_role" and "user" table. More over in my project there will be three users, one "admin", another "client" and another "special guest" and all will login through same login form.Client will register first and then login. for all client i want to give id "2" by default when they register. for admin will be id"1" and for guest id will be "3".How can i register all client with id "2". Please Kindly give the answer in simple way so that i could understand. my part of code is like this

$user = new User; // $user->name = $input['name']; $user->username = $input['username']; $user->email = $input['email']; $user->password = Hash::make($input['password']); $user->confirmation_code=$confirmation_code;
$data=[ 'name' => $input['name'], 'username' => $input['username'], 'subject' => 'Email confirmation', 'url' => URL::to('confirm/'.$confirmation_code), 'pathToImage' => public_path()."/images/birds-277a.jpg" ];

  Mail::send('account.verify', $data, function($message) {
  $message->to(Input::get('email'), Input::get('username'))
   ->subject('Verify your email address');
    });
   $success = $user->save();
   $user->roles()->attach(2);//when i  use this it gives error
    if($success)
    {
        return redirect('/')->with(['message' => 'Your account has been created and is pending email confirmation']);
    }

i want to give registered user id 2 Error like this: QueryException in Connection.php line 620: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (account_test.role_user, CONSTRAINT role_user_role_id_foreign FOREIGN KEY (role_id) REFERENCES roles (id) ON DELETE CASCADE ON UPDATE CASCADE) (SQL: insert into role_user (role_id, user_id) values (2, 6))

0 likes
4 replies
bobbybouwmann's avatar

@Ranjeet You can't demand answers here!

The message is pretty clear, the foreign constraint is not met so you can't insert it in the database. If you want our help we need your database structure as well

Please or to participate in this conversation.