php - Laravel Eloquent PostgreSQL save array Error : preg_replace(): Parameter mismatch

752

I'am working on Laravel 4 and Postgresql. I'am trying to store an array in Postgresql array field. Here's my table declaration :

CREATE TABLE person_title (
    id serial primary key,
    title text,
    name_list text[]
);

I try to insert a line using Eloquent :

public function create_person_title() {
    $title = Input::get('title');
    $name_list = Input::get('name_list');
    $data = [
        'title' : $title,
        'name_list' : $name_list,
    ];
    PersonTitle::create($data);
}

I get this error :

preg_replace(): Parameter mismatch, pattern is a string while replacement is an array

This error come from vendor/laravel/framework/src/Illuminate/Support/helpers.php:990 line.

I read on this question why do I get preg_replace() error when submitting a post form in Laravel? that this error occurs when we try to save an array.

But I really want to store an array on my Postgresql record (and I should be able to do that). Do you know a way to do that ?

445

Answer

Solution:

I found a way to store array in postgresql array text field by modify my list. Here is my new view :

public function create_person_title() {
    $title = Input::get('title');
    $name_list = Input::get('name_list');

    // Can't save a null value
    if (!$name_list) {
        $name_list = [];
    }

    $name_list = json_encode($name_list);
    $name_list = "'".preg_replace("#^\[(.*)\]$#", '{\1}', $name_list)."'";
    $name_list = DB::raw($name_list);

    $data = [
        'title' : $title,
        'name_list' : $name_list,
    ];
    PersonTitle::create($data);
}

I hope it will help you. Be careful if your array contains single quotes and others caracters like back slashes, you must escape them.

If nobody has a better way, I'm a buyer !

People are also looking for solutions to the problem: Calculate date using PHP

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.