skip to Main Content

Making job with new item created new saved item has 0 in id field when I try to pass this item in event.

Model item is made without autoincrement field (this id is passed from other app and must be saved):

Schema::create('items', function (Blueprint $table) {
    $table->unsignedSmallInteger('id')->primary();
    $table->boolean('active')->default(false);
});

Job Code:

class RMQItemCreated implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private array $data ;
    public function __construct(array $data)
    {
        $this->data = $data;
    }


    public function handle()
    {
        $item = Item::create(['id' => $this->data['id'], 'active' => true]);
        $item->load('itemLikedCounts'); // load related models

       ItemCreatedEvent::dispatch($item);
    }

I check in db and see that new item row was added with valid id.
But checking content of a item model in ItemCreatedEvent I see that id === 0

In model app/Models/Item.php :

<?php

namespace AppModels;

use IlluminateDatabaseEloquentModel;

class Item extends Model
{
    protected $table = 'items';
//    protected $primaryKey = 'id'; // if to uncomment this - the same results
    public $timestamps = false;

    protected $fillable = ['id', 'active'];
    protected $guarded = [];

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


    public function itemLikedCounts()
    {
        return $this->hasMany(AppModelsItemLikedCount::class);
    }

}

I tried to load relation itemLikedCounts, but it did not help…

"laravel/framework": "^9.41",

Thanks in advance!

2

Answers


  1. If your key is not auto-incrementing you have to specify that in the model:

    class Item extends Model
    {
        protected $table = 'items';
        public $incrementing = false; // here
    
        public $timestamps = false;
    
        protected $fillable = ['id', 'active'];
        protected $guarded = [];
    
        protected static function boot()
        {
            parent::boot();
        }
    
    
        public function itemLikedCounts()
        {
            return $this->hasMany(AppModelsItemLikedCount::class);
        }
    
    }
    
    Login or Signup to reply.
  2. Declare that your id is not incrementing in your model:

    public $incrementing = false;
    

    Instead of

    $item = Item::create(['id' => $this->data['id'], 'active' => true]);
    

    Try this:

    $item = new Item();
    $item->id = $this->data['id'];
    $item->active = true;
    $item->save();
    

    This should pass the ID to event!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search