1

I have a model called CroppedDocumentField, that have below $casts setup:

protected $casts = [
    'content' => 'array'
];

The migration looks like this:

Schema::create('cropped_document_fields', function(Blueprint $table){
      $table->increments('id');
      $table->unsignedInteger('document_id');
      $table->json('content')->nullable();
});

In my database, the content column seems to be stored like a string:

"{\"1\": [{\"row\": \"Bill Tc\\n\"}, {\"row\": \"Nathar\\n\"}, {\"row\": \"75839\\n\"}]}"

If I echo that out:

$document = CroppedDocumentField::Find(56);
dd(is_array($document->content));

This returns false.

When I insert the JSON to my database, I read it from a .txt file, that contains the JSON string:

{"1": [{"row": "Bill Tc\n"}, {"row": "Nathar\n"}, {"row": "75839\n"}]}

Then I insert it:

$file = "mytext.txt";
$content = file_get_contents($file);

//Add the text content
$this->document->cropped()->create([
     'content' => $content
]);

In my document model, I simply have a relationship to the CroppedDocumentField model:

//Document.php:
public function cropped()
{
    return $this->hasMany(CroppedDocumentField::class);
}

What am I doing wrong here?

4
  • @Tarasovych ah, fixed - it was a typo Commented May 20, 2019 at 8:23
  • What is the data type of the MySQL column? Is it VARCHAR? Commented May 20, 2019 at 8:24
  • The data type is JSON - will update my question to include the migration. Commented May 20, 2019 at 8:24
  • I believe the problem is because file_get_contents returns String, so that's why the data is stored like that. I have json column on my project, casting it to array is straight forward. Commented May 20, 2019 at 8:33

1 Answer 1

1

I tried casting json to array on my project and it worked as expected, what I believe the problem is the way you store the content. Please try changing it to this and let me know:

//Add the text content
$this->document->cropped()->create([
     'content' => json_decode($content) // convert string to json
]);
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, perfect! This converts the string to a valid JSON object. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.