21

I'm trying to save an array with options into a json datafield of my postgres database. I'm working with Laravel 5.5 and I'm using the extension "dimsav/laravel-translatable" for translations.

My model Question looks like this: namespace App;

use Illuminate\Database\Eloquent\Model;
use Dimsav\Translatable\Translatable;

class Question extends Model
{
    use Translatable;
    public $translatedAttributes = ['options', 'answer'];

    protected $casts = [
        'options' => 'array'
    ];
}

The model QuestionTranslation looks like this:

namespace App;

use Illuminate\Database\Eloquent\Model;

class QuestionTranslation extends Model
{

public $timestamps = false;
public $fillable = ['options', 'answer'];

}

And the store action in the QuestionsController:

 public function store(Request $request)
{
    $question = new Question();

    $options[1] = "test1";
    $options[2] = "test2";

    $question->answer = 1;
    $question->options = $options;

    $question->save();

}

When I try to store that data I get the error:

Illuminate \ Database \ QueryException
Array to string conversion (SQL: insert into "question_translations" ("locale", "answer", "options", "question_id") values (en, 1, test1, 18) returning "id")

When I use json_encode to cast $options myself, I can store it without problems.

Do you have any idea, why the laravel casting is not working? Maybe because of the translatable extension?

James Douglas
  • 3,328
  • 2
  • 22
  • 43
JayEJay
  • 263
  • 1
  • 2
  • 7
  • I got help here: https://laracasts.com/discuss/channels/laravel/laravel-getting-an-array-to-string-conversion-while-storing-an-array-into-a-json-database-field – JayEJay Dec 30 '17 at 13:44

3 Answers3

20

May be try to use this:

protected $casts = [
    'options' => 'json',
];

I tested it on MySQL however theoretically it should works also on postgresql.

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
-2

also use json_encode

public function store(Request $request)
{
    $question = new Question();

    $options[1] = "test1";
    $options[2] = "test2";

    $question->answer = 1;
    $question->options = json_encode($options);//json_encode

    $question->save();

}
Balaji
  • 9,657
  • 5
  • 47
  • 47