Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel convert an array to a model

i have an array as follows

      'topic' => 
  array (
    'id' => 13,
    'title' => 'Macros',
    'content' => '<p>Macros. This is the updated content.</p>
',
    'created_at' => '2014-02-28 18:36:55',
    'updated_at' => '2014-05-14 16:42:14',
    'category_id' => '5',
    'tags' => 'tags',
    'referUrl' => '',
    'user_id' => 3,
    'videoUrl' => '',
    'useDefaultVideoOverlay' => 'true',
    'positive' => 0,
    'negative' => 1,
    'context' => 'macros',
    'viewcount' => 60,
    'deleted_at' => NULL,
  )

I would like to use this array and convert/cast it into the Topic Model . Is there a way this can be done.

thanks

like image 324
Gagan Avatar asked May 14 '14 17:05

Gagan


2 Answers

Try creating a new object and passing the array into the constructor

$topic = new Topic($array['topic']);
like image 84
Laurence Avatar answered Nov 14 '22 09:11

Laurence


For creating models from a single item array:

$Topic = new Topic();
$Topic->fill($array);

For creating a collection from an array of items:

$Topic::hydrate($result);
like image 33
Liquinaut Avatar answered Nov 14 '22 08:11

Liquinaut