0
我在Laravel有一個Eloquent User模型。當我創建一個新用戶時,我想爲它自動創建一個令牌。我與觀察員一起做。但在觀察者中,我無法達到創建的模型,它想要創建一個新模型。Laravel 5.3 Observer無法訪問模型
我的用戶模型:
namespace App;
use App\Observers\UserObserver;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token'
];
public static function boot()
{
parent::boot();
static::observe(UserObserver::class);
}
}
我UserObserver
namespace App\Observers;
use App\User;
class UserObserver
{
public function creating(User $user)
{
$user->token = str_random(30);
}
}
當我創建一個新用戶,我得到Connection.php線異常
QueryException 763:
SQLSTATE [23000]:完整性 約束違例:19 NOT NULL約束失敗:users.name(SQL: 插入「用戶」(「token」,「updated_at」,「created_at」)值 (JQYUmmMrRRJT64VcFVA8UzkpY019u6,2016-10-31 14:33:35 ,2016-10-31 14:33:35))
你的SQL錯誤意味着你沒有* name *的值。你的觀察員已被「解僱」,你的代幣是JQYUmmMr ...。因此,如果您爲名稱傳遞值,也許在哪裏創建用戶。 – TheFallen
是的,它想要創建一個新的對象,而不是添加引發事件的那個標記值。 首先它創建一個新用戶: at Model :: create(array('_ token'=>'OHggG8VZCFxLSfGelxaHdIOYQSx05M7o16E2QKB2','name'=>'name','mail'=>'[email protected] ','password'=>'7X194HeFbwl!85>','password_confirmation'=>'7X194HeFbwl!85>')))RegistrationController.php中的第20行 在接收到事件並想要創建新用戶之後,任何屬性。 – tthlaszlo
請使用此代碼更新您的問題。 – TheFallen