Implicit conversion from data type nvarchar to varbinary(max) is not allowed. Use the CONVERT function to run this query
Hi guys,
I need to save a string into column image type to MSSQL but i recieve this error: Implicit conversion from data type nvarchar to varbinary(max) is not allowed. Use the CONVERT function to run this query.
I have found a solution, in my case file_content is a binary ( for me temporary file storage solution)
public function setFileContentAttribute($value)
{
if ('sqlsrv' === config('database.default')) { // todo or some other way to check if its sql server connection
return $this->attributes['file_content'] = DB::raw('CONVERT(VARBINARY(MAX), 0x' . bin2hex($value) . ')');
}
return $this->attributes['file_content'] = $value;
}
bin2hex for 2 reasons:
prevent sql injection since its unparameterized
to avoid utf-8 exceptions (binary not matching utf8 characters)