简体   繁体   中英

PHP / Laravel - Saving an array to database

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'
 ];

When I then want to fetch the data, I do this:

$field = StreamField::find(4);
return $field->coordinates['x'];

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

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

Now is this the correct way of doing it?

Yes, this is correct way of doing it. You can also save as XML as a string (whatever you prefer).

Altrought i would use getters and setters when saving coordinates in order to vertify input (if you need it). Because if any error occurs, the program would not write json but error (as a string).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM