Search code examples
laraveleloquentobservers

Laravel 5.4 Eloquent not Saving certain fields


I have been working on logging all user activities in Model events... But for some reason, the records are stored in the user_action table but the action_model field. This is my code. User Action Class `

class UserAction extends Model
{

  use SoftDeletes;

  protected $table = 'user_actions';

  /**
  *
  */

  protected $fillable = [
      'user_id','action', ' action_model', 'action_id'
  ];

  public function user()
  {
      return $this->belongsTo(User::class, 'user_id');
  }



}

`

UserActionObervable

    class UserActionObserver
{
    public function saved($model)
    {
        $type = $model->getTable();
        // dd($type); when dump the value exists
        if ($model->wasRecentlyCreated == true) {
            // Data was just created
            $action = 'created';
        } else {
            // Data was updated
            $action = 'updated';
        }
        if (Sentinel::check()) {
            UserAction::create([
                'user_id'      => Sentinel::getUser()->id,
                'action'       => $action,
                'action_model' => 'model', //I tried to pass in constant
                'action_id'    => $model->id
            ]);
        }
    }

    public function deleting($model)
    {
        if (Sentinel::check()) {
            UserAction::create([
                'user_id'      => Sentinel::getUser()->id,
                'action'       => 'deleted',
                'action_model' => $model->getTable(),
                'action_id'    => $model->id
            ]);
        }
    }
}

This is the schema

Schema::create('user_actions', function (Blueprint $table) {
      $table->increments('id');
      $table->integer('user_id')->unsigned()->nullable();
      $table->string('action');  // created / updated / deleted
      $table->string('action_model');
      $table->integer('action_id')->nullable(); 
      $table->timestamps();

      $table->engine = 'InnoDB';
      $table->foreign('user_id')->references('id')
            ->on('users')->onDelete('cascade');

    });

Solution

  • protected $fillable = [
        'user_id','action', ' action_model', 'action_id'
    ];
    

    Try to remove the space before action_model. The field in $fillable doesn't match the key you're passing into the create() method.