Reputation: 620
can someone help me to understand how can I use attribute casting if I am inserting data with DB seeder (and retrieve it)
this is part of the seeder
DB::table('events')->insert([
[
'title' => 'prizes',
'description' => serialize([
"text" => "General description..."
]),
'language' => 'en',
'time_start' => null,
'time_end' => null,
'lat' => null,
'lng' => null,
]
]);
this way I do have serialized data in my database, but when I do
$events = Event::with('user')->where('child','=',null)->get();
I get description is null
(don't worry about user its null by default)
this is my Event model
class Event extends Model
{
protected $table = 'events';
//
public function user()
{
return $this->hasOne('App\User','id');
}
protected $casts = [
'description' => 'array',
];
}
what am I missing here?
Upvotes: 0
Views: 847
Reputation: 3842
According to the doc, Eloquent array casting serializes array into JSON:
The array cast type is particularly useful when working with columns that are stored as serialized JSON
So you should insert it like this:
DB::table('events')->insert([[
'title' => 'prizes',
'description' => json_encode(["text" => "General description..."]),
'language' => 'en',
'time_start' => null,
'time_end' => null,
'lat' => null,
'lng' => null,
]]);
As a side note, serialize
belongs to PHP core and it does not produce JSON.
Upvotes: 2