Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hydrate an Eloquent model object from associative array with more keys than database columns

Tags:

php

eloquent

I have a database table called players with columns id, name, and team. The program is using Eloquent in the Slim framework.

<?php
// ... correct `require` and `use` lines ....

class Player extends Illuminate\Database\Eloquent\Model {
    protected $guarded = [];
}

$input = ['id'   => 4, 
          'name' => 'James Shelton', 
          'team' => 'Astrobots', 
          'year' => 1982];

$player = new Player($input);
$player->save();

The above code produces an error about the table not having a 'year' column. I have also tried the methods hydrate and fill.

What is the correct way to hydrate an Eloquent model object from an associative array and have the object only pay attention to array keys that match columns in the model's database table? Or am I incorrectly using the methods?

like image 925
jason Avatar asked Dec 08 '25 22:12

jason


1 Answers

You need to specify list of the fillable fields to match your db schema:

class Player extends Illuminate\Database\Eloquent\Model {
    protected $fillable = [
      'id', 
      'name', 
      'team'
    ] 
}

Read "Mass Assignment" part from https://laravel.com/docs/5.4/eloquent

like image 168
Alex Blex Avatar answered Dec 10 '25 10:12

Alex Blex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!