4

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,
   ]
);
STA
  • 30,729
  • 8
  • 45
  • 59
Heru Handoko
  • 79
  • 1
  • 10

2 Answers2

10
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;
        });       
    }
}
Sok Chanty
  • 1,678
  • 2
  • 12
  • 22
4

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!!

NikuNj Rathod
  • 1,663
  • 1
  • 17
  • 26
  • i choose this as accepted answer over Chanty's because it shows more complete codes, but both are working. thx for your effort. – Heru Handoko Oct 08 '20 at 05:03
  • I can see where you are going with this, checking that you have a valid user to avoid Exceptions, and such. But I think some explanation of `Auth::guard` and `app.guards.web` is warranted, and since you've introduced **soft delete**, you should really include a `deleted_by` field and appropriate updating function. – Orwellophile Oct 31 '21 at 13:26