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

jrdavidson's avatar

Seeds

I have 5 different roles and I need a percentage of each role to have user's with those roles so.

Role %
1       80
2      10
3      5
4   2
5      0

There is a reason for the 5th role just can't have any others be given that role at the moment.

for ($i = 1; $i < 300; $i ++)
{
    $roles = UserRole::lists('id');
        $confirmed = $faker->boolean($chanceOfGettingTrue = 95);
        $confirmation_code = null;

    if ($confirmed == 0)
    {
        $confirmation_code = str_random(30);
    }

            User::create([
                'first_name'        => $faker->firstName,
                'middle_name'        => $faker->firstName,
                'last_name'         => $faker->lastName,
                'username'          => $faker->userName,
                'email_address'     => $faker->email,
                'password'          => $faker->word,
                'confirmed'         => $confirmed,
                'confirmation_code' => $confirmation_code,
                'role_id'           => $faker->randomElement($roles)
    ]);
}
0 likes
34 replies
bobbybouwmann's avatar

I guess you can do something like this

$randomNumber = $faker->numberBetween(0, 100);

if ($randomNumber > 20) // around 80% of the roles will have role 1
    $role = 1;
elseif ($randomNumber > 10) // around 10% of the roles will have role 2
    $role = 2;
elseif ($randomNumber > 6) // around 6% of the roles will have role 3
    $role = 3;
else // around 4% of the roles will have role 4
    $role = 4;
1 like
jrdavidson's avatar

So you are suggesting. That's going to give me users with a role of 5 though.

for ($i = 1; $i < 300; $i ++)
        {
            $role = UserRole::lists('id');
            $random_number = $faker->numberBetween(0, 100);
            $confirmed = $faker->boolean($chanceOfGettingTrue = 95);
            $confirmation_code = null;

            if ($confirmed == 0)
            {
                $confirmation_code = str_random(30);
            }

            if ($random_number > 20) {
                $role = 1;
            } elseif ($random_number > 10) {
                $role = 2;
            } elseif ($random_number > 5) {
                $role = 3;
            } elseif ($random_number > 2) {
                $role = 4;
            } else {
                $role = 5;
            }

            User::create([
                'first_name'        => $faker->firstName,
                'middle_name'        => $faker->firstName,
                'last_name'         => $faker->lastName,
                'username'          => $faker->userName,
                'email_address'     => $faker->email,
                'password'          => $faker->word,
                'confirmed'         => $confirmed,
                'confirmation_code' => $confirmation_code,
                'role_id'           => $role
            ]);
        }
bobbybouwmann's avatar

Yea why not? It will give you the result you want right? You might refactor it to a function ;)

bashy's avatar

Why not just do randomNumber(1,5) for the role straight to it?

mstnorris's avatar

@bashy because @xtremer360 wants it to be weighted so that the majority of users have role 1.

@xtremer360 just change the if condition so that anything > 0 has a role of 4. Thus you won't get anyone with a role of 5.

bobbybouwmann's avatar

He wants a role 5 to show up 1% of the time and role 1 80% of the time and so on

I updated my answer to be more clear for others!

bashy's avatar

Ah yeah I see it now. Wondered what the table was about :P

If it's doing it 299 times and only has 0-100 for the range, it will do more?

jrdavidson's avatar

It looks good @bobbybouwmann however I'm not getting the desired results because I'm still getting more users with a role of 4 than I do with a 3 which should be the other way around.

bobbybouwmann's avatar

Well everything is random so there is a change that the number 3 is shown 8 times!

You can either assign a role based on $i like this:

for ($i = 1; $i < 300; $i ++)
        {
            $role = UserRole::lists('id');
            $confirmed = $faker->boolean($chanceOfGettingTrue = 95);
            $confirmation_code = null;

            if ($confirmed == 0)
            {
                $confirmation_code = str_random(30);
            }

            if ($i < 3) {
                $role = 4; // Get role 4, 4 times in the end results
            } elseif ($i < 13) {
                $role = 3; // Get role 3, 10 times in the end results
            } elseif ($i < 63) {
                $role = 2; // Get role 2, 50 times in the end results
            } else {
                $role = 1; // Get role 1, 236 times in the end results
            }

            User::create([
                'first_name'        => $faker->firstName,
                'middle_name'        => $faker->firstName,
                'last_name'         => $faker->lastName,
                'username'          => $faker->userName,
                'email_address'     => $faker->email,
                'password'          => $faker->word,
                'confirmed'         => $confirmed,
                'confirmation_code' => $confirmation_code,
                'role_id'           => $role
            ]);
        }

Of course you can play around with the numbers but you get the idea ;)

jrdavidson's avatar

I'd hate to place code in my application and come back to it a different time and be like what the heck did this do.

ArraySync's avatar

Welcome to the world of programming.. and every day coder life for those who work on projects for weeks months years.. solo or on a team.. it is what it is.. that's a fact of being a coder.. we evolve as we go. What you do now, you won't recognize a couple months from now..

mstnorris's avatar

@xtremer360 what are you worrying about?

  1. If you think it won't make sense down the line - don't write it now.
  2. As per your original question, what are you having trouble with?
ArraySync's avatar

You will never write functioning code for real world use with that mentality.. cause nothing's going to make sense.. coders evolve and improve over time.. technology advances newer methods become available.. Nothing you do today from a coding standpoint will make sense down the road.. There is always a new standard, better way, optimization technique that becomes a thing for a while till the next thing comes along..

jrdavidson's avatar

@ArraySync @mstnorris @bobbybouwmann I guess I need to reconsider how I want to handle roles and permissions and storing them in the database because what I want from my application is users to be be assigned role(s) which could prevent them from accessing certain parts of my application. So I would need to set up permissions for those roles however I need to take into consideration the what if I want to continue to keep a user at a certain level but change one of the permissions of that user and not the role specific so they can/cannot perform a certain task. What should be db structure be then for this situation? Should I have a users table, roles table, then a user_roles table that is the pivot table.

mstnorris's avatar
Level 55

You'd have the following

Permission model

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Permission extends Model {

    protected $fillable = [
        'name'
    ];

    public function roles()
    {
        return $this->belongsToMany('App\Role')->withTimestamps();
    }

}

Role model

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model {

    protected $fillable = [
        'name'
    ];

    public function users()
    {
        return $this->belongsToMany('App\User');
    }

    public function permissions()
    {
        return $this->belongsToMany('App\Permission');
    }

}

User model

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model {

    protected $fillable = [
        'name'
    ];

    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }

}

users table

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function(Blueprint $table)
        {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password', 60);
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('users');
    }

}

permissions table

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePermissionsTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('permissions', function(Blueprint $table)
        {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('name')->unique();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('permissions');
    }

}

roles table

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateRolesTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('roles', function(Blueprint $table)
        {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('name')->unique();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('roles');
    }

}

role_user pivot table

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateRoleUserTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('role_user', function(Blueprint $table)
        {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->integer('role_id')->unsigned()->index();
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->integer('user_id')->unsigned()->index();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('role_user');
    }

}

permission_role pivot table

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePermissionRoleTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('permission_role', function(Blueprint $table)
        {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->integer('permission_id')->unsigned()->index();
            $table->foreign('permission_id')->references('id')->on('permissions')->onDelete('cascade');
            $table->integer('role_id')->unsigned()->index();
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('permission_role');
    }

}
jrdavidson's avatar

@mstnorris One question again thanks. What does the integer level field signify for the permissions table?

mstnorris's avatar

@xtremer360 let me know if you need anything else.

Do you use seeders? If so I can get you going with that too.

mstnorris's avatar

Sorry, I will remove it, I was using that in my project. You can ignore it.

mstnorris's avatar

@xtremer360 this will get you going. They're just examples, but if you have any questions please ask away.

<?php

use Carbon\Carbon;
use Faker\Factory as Faker;
use App\Permission;
use App\Role;
use App\User;

class ConstantsTableSeeder extends Seeder
{
    public function run()
    {
        $faker = Faker::create();

        /*
         * Static User Accounts
         */

        // Static Account
        $static_user = User::create([
            'name'       => 'John Appleseed',
            'email'      => 'johnappleseed@example.com',
            'password'   => bcrypt('password'),
            'created_at' => Carbon::now(),
            'updated_at' => Carbon::now()
        ]);

        /*
         * Random User Accounts
         */

        foreach (range(1, 50) as $index) {
            User::create([
            'name'       => $faker->name,
            'email'      => $faker->email,
            'password'   => bcrypt('password'),
            'created_at' => Carbon::now(),
            'updated_at' => Carbon::now()
            ]);
        }

        /*
         * Roles
         */

        // Super Administrator (Role)
        $superSystemAdminR = Role::create([
            'name'       => 'Super System Administrator',
            'created_at' => Carbon::now(),
            'updated_at' => Carbon::now()
        ]);

        // Administrator (Role)
        $systemAdminR = Role::create([
            'name'       => 'System Administrator',
            'created_at' => Carbon::now(),
            'updated_at' => Carbon::now()
        ]);

        /*
         * Permissions
         */

        // Super System Administrator (Permission)
        $superSystemAdminP = Permission::create([
            'name'       => 'Super System Administrator',
            'level'      => '1000',
            'created_at' => Carbon::now(),
            'updated_at' => Carbon::now()
        ]);

        // Administrator (Permission)
        $systemAdminP = Permission::create([
            'name'       => 'System Administrator',
            'level'      => '500',
            'created_at' => Carbon::now(),
            'updated_at' => Carbon::now()
        ]);

        /*
         * Detailed User Accounts with Roles and Permissions
         */

        $static_user->roles()->attach($superSystemAdminR);
        $supersysadmin->roles()->attach($superSystemAdminR);
        $sysadmin->roles()->attach($systemAdminR);

        $superSystemAdminR->permissions()->attach($superSystemAdminP);
        $systemAdminR->permissions()->attach($systemAdminP);
        
    }

}
jrdavidson's avatar

I thought permissions were like: can_create_posts or can_update_posts or something to that affect.

Next

Please or to participate in this conversation.