Support the ongoing development of Laravel.io →
Database Eloquent

Sorry if this has already been addressed, but I didn't find anything by searching Binary Data on the forums.

I am trying to save data that has been created by the PHP inet_pton() function into an MSSQL BINARY(16) field, and I am getting the following error:

Illuminate\Database\QueryException","message":"SQLSTATE[42000]: [Microsoft][SQL Server Native Client 11.0][SQL Server]Implicit conversion from data type nvarchar to binary is not allowed. Use the CONVERT function to run this query.

I have looked pretty thoroughly on the web for any answer/example of how to do this with no success.

Anyone have any ideas on how to do this?

A condensed version of the Table & Code is below.

Thanks in advance.

ewb

Table:

CREATE TABLE dbo.IPRange
(
	 iprange_id  BIGINT IDENTITY(1,1) NOT NULL,
	 campaign_id  BIGINT NOT NULL,
	 company_name NVARCHAR(500) NULL,
	 ip_start BINARY(32) NOT NULL,
	 ip_end BINARY(32) NOT NULL,
...
}

Code:

$ipRange = new \IPRange();
$ipRange->ip_start			= '192.168.1.1';
$ipRange->ip_end			= '192.168.1.255';
$ipRange->company_name		= 'ABC Company';
$ipRange->domain			= 'http://www.abccompany.com';
$ipRange->save();

class IPRange extends Eloquent
{
	public function save(array $options = array())
	{
		if ( isset($this->ip_start) && self::isIP($this->ip_start) )
			$this->ip_start = self::toPackedIPv6($this->ip_start);

		if ( isset($this->ip_end) && self::isIP($this->ip_end) )
			$this->ip_end = self::toPackedIPv6($this->ip_end);

		return parent::save($options);
	}

	public static function isIP($ipString)
	{
		if ( filter_var($ipString, FILTER_VALIDATE_IP) !== false  )
			return true;

		return false;
	}

	public static function toPackedIPv6($ipString)
	{
		$packed	= inet_pton($ipString);

		return $packed;
	}
}
Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

ebaer ebaer Joined 17 Sep 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.