Moum
Moum

Reputation: 93

Store multiple objects in json column

I have table with some json column. I want to store multi objects in the json column in Laravel.

My json column look like this "position":[{"lat" : 500, "lon" : 5000, "date":"2020:04:21 16:58:23"}].

this is a function in a service that , i call in my controller

 public static function savePositionCamion($id_tournee, $position)
    {
        $geoTour = GeoTournee::where('geo_tournee.id_tournee', $id_tournee)->first(['position']);

        if (!$geoTour) {
            $geoTournee = new self();
            $geoTournee->id_tournee = $id_tournee;
            $geoTournee->position = $position;
            return $geoTournee->save() ? $geoTournee : false;
        } else {
            $arr_pos = json_decode($geoTour->position);
            dd($arr_pos);

        }


    }

in the controller i call the function like this

$geoTourne = GeoTournee::savePositionCamion($request->id_tournee, json_encode($request->position));

anyone can help me to achieve this ! thank's

Upvotes: 0

Views: 1135

Answers (1)

TsaiKoga
TsaiKoga

Reputation: 13394

The array cast type is particularly useful when working with columns that are stored as serialized JSON. You have JSON or TEXT field type that contains serialized JSON, adding the array cast to that attribute will automatically deserialize the attribute to a PHP array when you access it on your Eloquent model:

class GeoTournee extends Model
{
    ...
    protected $casts = [
        'position' => 'array',
    ];
    ...
}

So you can save this json field like this:

$geoTournee->position = $position;
$geoTournee->save();

Accessing the position attribute and it will automatically be deserialized from JSON into a PHP array. When you set the value of the position attribute, the given array will automatically be serialized back into JSON for storage:

And you don't need to create savePositionCamion function, you can use firstOrCreate instead:

GeoTournee::firstOrCreate(['id_tournee' => $id_tournee], [ 'position' => $position ]);

Upvotes: 2

Related Questions