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

Jawsh's avatar

Eloquent does not deal with binary information correctly in PostgreSQL.

It's impossible to insert binary data using PostgreSQL with Eloquent

Postgres requires that binary data is marked with a special PDO attribute on bindValue, PDO::PARAM_LOB. Not doing this raises the following error:

SQLSTATE[22021]: Character not in repertoire: 7 ERROR: invalid byte sequence for encoding "UTF8": 0x ...

This is despite the fact that the column type is correct, bytea. Postgres chokes because it's passed with PDO::PARAM_STR.

How can I fix this so that I can insert binary data in Postgres, as I can with MySQL, MariaDB, and SQLite?

By reading the documentation, I thought that perhaps if I created my Postgres database with the SQL_ASCII character set, it wouldn't do any validation, which is a hack to get around this bug. Unfortunately, this led to even more breakage in my Laravel application; model attributes started turning into stream resources sometimes, and failing with this error other times:

SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for type bytea (SQL: insert into "captcha" ("client_ip", "solution", "hash", "created_at") values , VmG, �M��fany�W3xO˭�ҏ\, 2015-11-07 07:59:46) returning "

And here's a dd() of the stream resource (which is just an attribute on my Eloquent model):

stream resource @382 ▼
  stream_type: "MEMORY"
  mode: "w+b"
  unread_bytes: 0
  seekable: true
  timed_out: false
  blocked: true
  eof: false
  options: []
}

This problem has been around since Laravel 4 and an entire library exists to deal with it. This does not work with Laravel 5.

http://packalyst.com/packages/package/ooxif/laravel-query-param

The PostgreSQL implementation of Eloquent needs some way of knowing if it should pass in PDO::PARAM_LOB instead of PDO::PARAM_STR. I'm not sure the specifics, but I think this should be the case with any binary item.

0 likes
1 reply
Jawsh's avatar

I'd like to add that I have created a formal issue with the Laravel Framework. If I can figure out how to incorporate this functionality with the Illuminate/Database I will submit a pull request.

Please or to participate in this conversation.