belongsTo(Carrier::class, 'carrier_id'); } public function clientCarrier(): BelongsTo { return $this->belongsTo(ClientCarrier::class, 'client_carrier_id'); } public function client(): BelongsTo { return $this->belongsTo(Client::class, 'client_id'); } public function equipment(): BelongsTo { return $this->belongsTo(Equipment::class, 'equipment_id'); } // Booted method to handle model events protected static function booted() { static::saving(function ($truck) { // Set the geo ID if not already set if (!$truck->empty_geo_id && $truck->empty_city && $truck->empty_state_code) { $truck->empty_geo_id = $truck->getGeoId($truck->empty_city, $truck->empty_state_code, $truck->empty_country_code); } // Automatically set the client ID from the authenticated user if (!$truck->client_id) { $truck->client_id = auth()->user()->client_id; } // Automatically set the carrier ID from the related client carrier if (!$truck->carrier_id && $truck->clientCarrier) { $truck->carrier_id = $truck->clientCarrier->carrier_id; } }); } // Method to calculate geo ID based on city, state, and country private function getGeoId($city, $stateCode, $countryCode) { // Translate "USA" to "US" if (strtoupper($countryCode) === 'USA') { $countryCode = 'US'; } $stateId = \DB::table('states') ->where('code', $stateCode) ->value('id'); if (!$stateId) { return null; } $countryId = \DB::table('countries') ->where('name_code', $countryCode) ->value('id'); if (!$countryId) { return null; } return \DB::table('geo') ->where('city', $city) ->where('state_id', $stateId) ->where('country_id', $countryId) ->value('id'); } }