jeudi 23 janvier 2020

What is the best way to bind a non nullable foreign key on a new created entity with laravel

I'm currently learning laravel 6.x and I have an issue when creating a new entity with a non nullable foreign key.

For security purpose my user_id foreign key is not mass assignable as you can see below

 /**
    * The attributes that are mass assignable.
    *
    * @var array
    */
   protected $fillable = [
       'city', 'zipcode', 'age', 'height', 'weight', 'profession', 'goal', 'sport', 'injury', 'health_issue', 'source'
   ];

And when I want to save my new created profile like this

$profile->user()->associate($user);
$profile->save();

I have a sql error because user_id can't be null

I could make the user_id mass assignable but I don't want to for security reason or to make the user_id nullable, but I don't want it either.

I came up with that solution but I'm not satisfied

Dispatching an event at 'creating'

  /**
 * The event map for the model.
 *
 * @var array
 */
protected $dispatchesEvents = [
    'creating' => ProfileCreated::class
];

The event

/**
 * @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');
}

And finally the listener where I'm adding user to the profile

  /**
 * Handle the event.
 *
 * @param  ProfileCreated  $event
 * @return void
 */
public function handle(ProfileCreated $event)
{
    $event->profile->user()->associate($event->user);
}

I might encounter this problem many times while working on my project, so I want to be sure what would be the best approach in such cases.

Thank you !



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire