created_by & updated_by in Laravel's updateOrCreate

Viewed 5820

With "updateOrCreate" command, how do we update "created_by" when insert new rows,

and update "updated_by" when it updates?

$flight = App\Flight::updateOrCreate(
   [   
       'departure' => 'Oakland', 
       'destination' => 'San Diego'
   ],
   [
      'price' => 99,
      'created_by' => $user_id,
      'updated_by' => $user_id,
   ]
);
2 Answers
class Model extend Model {
     public static function boot()
     {
        parent::boot();
        static::creating(function($model)
        {
            $user = Auth::user();           
            $model->created_by = $user->id;
            $model->updated_by = $user->id;
        });
        static::updating(function($model)
        {
            $user = Auth::user();
            $model->updated_by = $user->id;
        });       
    }
}

You can try this solution for your problem:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Auth;

class Flight extends Model {

    use SoftDeletes;
    use Notifiable;

    /**
     * Table name
     * @var variable
     */
    public $table = 'flight';

     /**
     * For Soft delete
     * @var array
     */
    protected $dates = ['deleted_at'];

    protected static function boot() {
        parent::boot();

        static::creating(function ($model) {
            $model->created_by = is_object(Auth::guard(config('app.guards.web'))->user()) ? Auth::guard(config('app.guards.web'))->user()->id : 1;
            $model->updated_by = NULL;
        });

        static::updating(function ($model) {
            $model->updated_by = is_object(Auth::guard(config('app.guards.web'))->user()) ? Auth::guard(config('app.guards.web'))->user()->id : 1;
        });
    }
}

It will be helpful. Thanks!!

Related