1

Hi I'm using a json column in migrations and trying to save values to data via model. Here is my migration,

Schema::create('notifications', function (Blueprint $table) {
    $table->increments('id');
    $table->json('title');
    $table->json('message')->nullable();
    $table->timestamps();
});

And this is my model code,

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Spatie\Translatable\HasTranslations;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasOne;

class Notification extends Model

{
    use HasTranslations;

    public $translatable = ['title','message'];

    protected $fillable = [
        'title','message'
    ];

},

And this is my insert code,

$notification = new Notification();

$notification_title = [
    'en' => 'Request created',
    'it' => 'Richiesta creata',
];
$notification_title = json_encode($notification_title);

$notification_message = [
    'en' => 'Request created',
    'it' => 'Richiesta creata',
];
$notification_message = json_encode($notification_message);

$notification->title = $notification_title;
$notification->message = $notification_message;
$notification->save();

Seems like json fields are not saving properly.

1 Answer 1

5

Replace json_encode() with JSON casts:

class Notification extends Model
{
    protected $casts = [
        'title' => 'array',
        'message' => 'array',
    ];
}
Sign up to request clarification or add additional context in comments.

5 Comments

How does the data get saved?
Something like this - {"it": "{\"en\":\"Request created\",\"it\":\"Richi... Sorry but it's hard to copy also :(
Sorry, I missed that you are already applying json_encode(). What happens when you leave the casts and remove $notification_title = json_encode($notification_title); and $notification_message = json_encode($notification_message);?
Then works fine :) add it as an answer. Thanks so so much
I've added it to my answer.

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.