Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

illmatic's avatar

Storing Addresses

Looking for suggestions on the best way to store addresses.

Currently I have many models that need addresses so I decided to use the One To One (Polymorphic) relationship

    public function address()
    {
        return $this->morphOne('App\Address','imageable');
    }

but I'm not sure this is the best way to store this data since I anticipate many redundant entries which isn't good use of storage. What have others done to use a single entry in the database with a list of imageable ids who leverage that address.

0 likes
5 replies
bugsysha's avatar

Usually, I store it on the same model, like Company or whatever model that address belongs to.

I had only one use case where I needed only one version of a specific address to exist and it was a foreign key that was used by many models. If that is the case for you, then do something firstOrCreate() for addresses.

wingly's avatar

I personally store those kind of stuff in json columns $table->json('address');

illmatic's avatar

I guess I should have mentioned that eventually I will want to leverage these addresses for radius based searches. Thanks for the input

wingly's avatar

Nobody is stoping you :)

    public function scopeCloseTo($query, $lat, $lon, $distance = 60000)
    {
        return $query->whereRaw('
            ST_Distance_Sphere(
		point(JSON_EXTRACT(address, "$.lon"), JSON_EXTRACT(address, "$.lat")),
                point(?, ?)
            ) < ?
        ', [
            $lon,
            $lat,
            $distance,
        ]);
    }
bugsysha's avatar

It's hard only if you make it that way :D

Please or to participate in this conversation.