Reputation: 827
Trying to create a new record for my Account
model.
My model has the following structure: 'title','information','image','combat','quest','price'
I also have 24 more items on my model that are considered as skills
I want to make it possible that for those 24 items I can make a loop in my create method, so that I don't have to manually add all the skills in my create.
Model looks like the following:
public function up()
{
Schema::create('accounts', function (Blueprint $table) {
$table->increments('id');
$table->integer('price');
$table->string('image_url');
$table->integer('quest_points');
$table->string('title');
$table->string('information');
$table->integer('attack');
$table->integer('defence');
$table->integer('strength');
$table->integer('constitution');
$table->integer('cooking');
$table->integer('construction');
$table->integer('farming');
$table->integer('crafting');
$table->integer('firemaking');
$table->integer('fishing');
$table->integer('fletching');
$table->integer('herblore');
$table->integer('hunter');
$table->integer('magic');
$table->integer('mining');
$table->integer('prayer');
$table->integer('ranged');
$table->integer('runecrafting');
$table->integer('slayer');
$table->integer('smithing');
$table->integer('agility');
$table->integer('thieving');
$table->integer('woodcutting');
$table->integer('total_level');
$table->integer('combat_level');
$table->timestamps();
});
}
My create method:
public function store(Request $request)
{
$account = $request->all('title','description','image','combat','quest','price');
$skills = $request->get('skill');
// array of 24 items, example -> 'attack' = 52;
Account::create([
'title' => $account['title'],
'price' => $account['price'],
'information' => $account['description'],
'image_url' => $account['image'],
'combat_level' => $account['combat'],
'quest_points' => $account['quest'],
// I would do the following normally
'attack' => $skills['attack'],
'defence' => $skills['defence'],
// ....
// possible to do this with a loop of the array $skills?
]);
}
Upvotes: 1
Views: 60
Reputation: 770
Give the same names to the input fields as table columns after that you can create record using the following. It should work
$mergedArray = array_merge($account, $skills);
Account::create($mergedArray);
Upvotes: 4
Reputation: 585
First make sure the name of the input fields is the same name as table records after that you can create record using the following:
Account::create($skills);
And If you want to insert many skills into account model you can use insert
method
$skills = array(
$array_of_skills,
$array_of_skills_,
//...
);
Account::insert($skills);
Upvotes: 3