В настоящее время я изучаю laravel 6.x, и у меня возникла проблема при создании нового объекта с необнуляемым внешним ключом.
В целях безопасности мой внешний ключ user_id не назначается массово, поскольку вы см. ниже
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'city', 'zipcode', 'age', 'height', 'weight', 'profession', 'goal', 'sport', 'injury', 'health_issue', 'source'
];
И когда я хочу сохранить свой новый созданный профиль, как этот
$profile->user()->associate($user);
$profile->save();
У меня ошибка sql, потому что user_id не может быть нулевым
Я мог бы назначить массу user_id назначаемой, но я не хочу по соображениям безопасности или сделать user_id обнуляемым, но я тоже этого не хочу.
Я придумал это решение, но я Я не удовлетворен
Отправка события при «создании»
/**
* The event map for the model.
*
* @var array
*/
protected $dispatchesEvents = [
'creating' => ProfileCreated::class
];
Событие
/**
* @var Profile $profile
*/
public $profile;
/**
* @var User $user
*/
public $user;
/**
* Create a new event instance.
*
* @param Profile $profile
* @return void
*/
public function __construct(Profile $profile)
{
$this->profile = $profile;
$this->user = Auth::user();
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
И, наконец, слушатель, где я добавляю пользователя в профиль
/**
* Handle the event.
*
* @param ProfileCreated $event
* @return void
*/
public function handle(ProfileCreated $event)
{
$event->profile->user()->associate($event->user);
}
Я мог сталкиваться с этой проблемой много раз во время работы над моим проектом, поэтому я хочу быть уверен, что будет лучший подход в таких случаях.
Спасибо!