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

Time:06-02

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.

CodePudding user response:

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;
        }
    }
}

CodePudding user response:

You can use try package.

https://github.com/onlinepets/laravel-conditional-migrations

I hope it will help you

  • Related