skip to Main Content

I’m trying to insert json into a mysql column table, I’ve try json_encode([...]) to insert into my json column, but there’s an error Array to string conversion

enter image description here

I would like to insert a json field, I’m not sure why this happen, so I’ll be helpful that this works.

2

Answers


  1. Use attribute casting in your model

        protected function casts(): array
    {
        return [
            'options' => 'array',
        ];
    }
    

    https://laravel.com/docs/11.x/eloquent-mutators#array-and-json-casting

    Login or Signup to reply.
  2. It seems like you might be trying to insert a json or array to doc_content field, so For that in your model you need to add Casts, it identifies special types of field or problem like you are facing might come. Casts is used for identifying special type of fields type, like json or array. So in your model you need to define

    Protected $casts = ['doc_content' => 'json'];
    

    And If you want to directly save array, then you can give,

    Protected $casts = ['doc_content' => 'array'];
    

    Also pls make sure you have made an json field while making table through migration.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search