*/ protected $fillable = [ 'physical_item_id', 'supplier_id', 'count', 'original_count', 'original_count_invoice', 'price', 'bought', 'description', 'note', 'country_of_origin_id', 'on_the_way', 'stock_batch_id', 'created_by', 'updated_by', ]; protected $appends = [ 'count_stocked', 'counted', ]; /** * The attributes that should be cast. * * @var array */ protected $casts = [ 'bought' => 'date', 'on_the_way' => 'boolean', 'counted' => 'boolean', ]; public function getCountedAttribute(): int { // calls your existing method, which will // loadMissing the relations if needed return $this->statusHistory()->where('stock_entries_status_id', 2)->exists(); } public function getCountStockedAttribute(): int { // calls your existing method, which will // loadMissing the relations if needed return $this->countStockedItems(); } /** * Get the physical item associated with the stock entry. */ public function physicalItem(): BelongsTo { return $this->belongsTo(PhysicalItem::class, 'physical_item_id'); } /** * Get the supplier associated with the stock entry. */ public function supplier(): BelongsTo { return $this->belongsTo(Supplier::class, 'supplier_id'); } /** * Get the stock batch associated with the stock entry. */ public function stockBatch(): BelongsTo { return $this->belongsTo(StockBatch::class); } public function statusHistory(): HasMany { return $this->hasMany(StockEntryStatusHistory::class, 'stock_entries_id'); } /** * Get the attributes for this stock entry. */ public function attributes(): BelongsToMany { return $this->belongsToMany( StockAttributes::class, 'stock_entry2attributes', 'stock_entry_id', 'stock_attributes_id' )->withPivot('stock_attribute_value_id'); } public function countryOfOrigin(): BelongsTo { return $this->belongsTo(OriginCountry::class, 'country_of_origin_id'); } public function sections(): BelongsToMany { return $this->belongsToMany( StockSection::class, 'stock_entries2section', 'entry_id', 'section_id' ) ->using(StockEntrySection::class) ->withPivot('count') ->withTimestamps(); } /** * Return each storage “address” string: * Room-Line-Rack-Shelf-Position-Section * * @return string[] */ public function storageAddresses(): array { // eager-load the whole hierarchy if not already $this->loadMissing('sections.position.shelf.rack.line.room'); return $this->sections ->map(function (StockSection $section) { $pos = $section->position; $shelf = $pos->shelf; $rack = $shelf->rack; $line = $rack->line; $room = $line->room; return sprintf( '%s-%s-%s-%s-%s-%s', $room->room_symbol, $line->line_symbol, $rack->rack_symbol, $shelf->shelf_symbol, $pos->position_symbol, $section->section_symbol ); }) ->toArray(); } public function countStockedItems(): int { return (int) $this ->sections() ->sum('stock_entries2section.count'); } }