Search code examples
phplaravellaravel-9

How do i set default value with conditional in laravel migrate?


So i create a column with

$table->enum('role', ['admin', 'customer'])->default('customer');

and i want a table with

if email with @domain.com then assign into role admin 
else go to customer.

is there a way to do this in migration? or do i need to set up in model? i'm a beginner in php and Laravel so please give me detailed instruction.


Solution

  • I invite you to create an observer on your Eloquent model.

    You can read the doc at: https://laravel.com/docs/9.x/eloquent#observers

    Remember to create a PHP enum to check your roles. This will allow you to more easily add roles or do additional checks in your code without having magic values:

    <?php
    enum Role : string
    {
        case ADMIN = 'admin';
        case CUSTOMER = 'customer';
    }
    

    The creating event seems to be the most suitable since it will be observed during insertion :

    <?php
     
    namespace App\Observers;
     
    use App\Models\User;
     
    class UserObserver
    {
        /**
         * Handle the User "creating" event.
         *
         * @param  \App\Models\User  $user
         * @return void
         */
        public function creating(User $user)
        {
            // Your logic here
            if(str_ends_with($user->email, '@domain.com')) {
                $user->role = Role::ADMIN->value;
            } else {
                $user->role = Role::CUSTOMER->value;
            }
        }
    }