Search code examples
phpmysqllaravelipvarbinary

Laravel varbinary(ip) using with where not working


I'm using varbinary(16) to store ips in the database like described here https://stackoverflow.com/a/24270808/5717102 .

To convert to human readable and to binary i use inet_ntop and inet_pton. This works well, but it won't work with the where query.

MyModel::where('ip', $ip)->get();

What am I missing, shouldn't it work? I already googled, but wasn't able to find any usefull information.


Solution

  • Accessors and Mutators won't work with queries. So you should access it as MyModel::where('ip', inet_pton($ip))->get()

    You can further just create a scope and move the logic to the model if you want to extract it out.

    public function scopeWhereIp($query, $ip)
    {
      return $query->where('ip', inet_pton($ip));
    }
    

    and access it as

    MyModel::whereIp($ip)->get()