Level 1
Would it be better to use a seed file? How would I do that?
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I used Entrust to add roles to my users. Currently the roles are created and applied in the routes:
Route::get('/start', function()
{
$subscriber = new Role();
$subscriber->name = 'Subscriber';
$subscriber->save();
$author = new Role();
$author->name = 'Author';
$author->save();
$read = new Permission();
$read->name = 'can_read';
$read->display_name = 'Can Read Posts';
$read->save();
$edit = new Permission();
$edit->name = 'can_edit';
$edit->display_name = 'Can Edit Posts';
$edit->save();
$subscriber->attachPermission($read);
$author->attachPermission($read);
$author->attachPermission($edit);
$user1 = User::find(1);
$user2 = User::find(2);
$user1->attachRole($author);
$user2->attachRole($subscriber);
});
How do I move this function to the controller so that it is not necessary to go to page /start to create and apply roles?
You should use a seed file indeed
Create a new file called RoleTableSeeder .php in the database/seeds directory and fill it with this as an example
<?php
use App\Role;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class RoleTableSeeder extends Seeder {
public function run()
{
DB::table('roles')->delete();
User::create(array(
'name' => 'Admin'
));
}
}
Now you open up the DatabaseSeeder.php file in the seeds directory and it should look like this
public function run()
{
Model::unguard();
$this->call('UserTableSeeder');
$this->call('RoleTableSeeder '); // As an example
}
Please or to participate in this conversation.