所以我創建了一個列
$table->enum('role', ['admin', 'customer'])->default('customer');
我想要一張桌子
if email with @domain.com then assign into role admin
else go to customer.
有沒有辦法在遷移中做到這一點?還是我需要在模型中設定?我是 php 和 Laravel 的初學者,所以請給我詳細的說明。
uj5u.com熱心網友回復:
我邀請你在你的 Eloquent 模型上創建一個觀察者。
您可以在以下位置閱讀檔案:https ://laravel.com/docs/9.x/eloquent#observers
請記住創建一個 PHP 列舉來檢查您的角色。這將允許您更輕松地添加角色或在代碼中進行額外檢查,而無需使用魔法值:
<?php
enum Role : string
{
case ADMIN = 'admin';
case CUSTOMER = 'customer';
}
該creating事件似乎是最合適的,因為它會在插入期間被觀察到:
<?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;
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/485543.html
