oliverbusk
5 months ago

Saving an array to database

Posted 5 months ago by oliverbusk

Hi all

I have a hard time understanding the basic attribute casting in Laravel.

I want to store some coordinates in my database:

$coordinates = [
     'x' => 100,
     'y' => 60,
     'h' => 250,
     'w' => 250,
];

To save the coordinates, I do this:

$field = StreamField::find(4);
$field->coordinates = $coordinates;
$field->save();

I have declared belows casts on my Field model:

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

In my migration, the coordinates column is created like this:

$table->json('coordinates')->nullable();

Now is this the correct way of doing it?

Please sign in or create an account to participate in this conversation.