Andreza Vieira
Andreza Vieira

Reputation: 27

Laravel 5.1: Method "create" receiving a banch of data

I have a form that receives data from Person and Address. I want to save specific data in the Person table and in the Address table.

I'm using the method "create" from the Person model to persist first the Person, this method receives as parameter an array of data (related to Person and Address). So, I get an error "SQLSTATE[42S22]: Column not found ...", because it tries to insert Address value into Person table.

How to handle it?

Thanks in advance.

Upvotes: 0

Views: 61

Answers (2)

Alfonz
Alfonz

Reputation: 1020

I assume you have a Person model with hasOne or hasMany Address.

You shouldn't pass the address attributes in the Person's create method. What you can do instead is first create the Person, then save an Address object related to that person.

For example:

$formData = ['name' => 'John', 'age' => 25, 'country' => 'US'];

$person = Person::create([
    'name' => $formData->name,
    'age' => $formdata->age
]);

$address = new Address([
    'name' => $formData->country
]);

// Save $address related to $person
// for ex. if Person hasOne Address:
$person->address()->save($address);

See Inserting & Updating Related Models section in the docs.

Upvotes: 0

Robert P
Robert P

Reputation: 96

You should be setting either the $fillable or $guarded property on your Model's

for example, if your request contains the following data:

[ 
  'name' => 'Bill Mickelson',
  'street' => '123 Test Lane',
  'city' => 'Baltimore',
  'state' => 'Maryland'
]

and 'name' relates to Person, but the other 3 relate to Address you would do the following...

in Person.php:

protected $fillable = [ 'name' ];

in Address.php:

protected $fillable = [ 'street', 'city', 'state' ];

After this, when you call create(), only the fields specified in $fillable will be populated.

As an aside, you can also just set $guarded to specify which SHOULDN'T be fillable, i.e. if each of these model's has an 'id' and you want everything else to be fillable, you can do:

protected $guarded = [ 'id' ];

Upvotes: 1

Related Questions