Internal applications need controlled access. Our app allows open registration but requires administrator approval via a simple checkbox before users can log in.
Let's start by creating our Roles table:
Migration
Schema::create('roles', function (Blueprint $table) { $table->id(); $table->string('name'); $table->timestamps();});
Then, we can create our Model with a few Role constants:
app/Models/Role.php:
class Role extends Model{ public const ADMIN = 1; public const USER = 2; protected $fillable = [ 'name', ];}
Of course, for this to work - we need to seed these constants:
database/seeders/DatabaseSeeder.php:
use App\Models\Role; // ... public function run(): void{ // User::factory(10)->create(); Role::create(['name' => 'admin']); Role::create(['name' => 'user']); }
Once this is done, we can add a Role field to our Users table:
Migration
Schema::table('users', function (Blueprint $table) { $table->foreignId('role_id')->constrained();});
Then we can add the field to the user Model $fillable array and a relationship:
app/Models/User.php:
use Illuminate\Database\Eloquent\Relations\BelongsTo; // ... class User extends Authenticatable{ // ... protected $fillable = [ 'name', 'email', 'password', 'role_id', ]; // ... public function role(): BelongsTo { return $this->belongsTo(Role::class); }}
Last, we can seed our "super admin" user: