Использование Laravel 5.7.
Разработка приложения с множеством представлений, содержащих формы.
В этом представлении:
- есть одно (только одно) поле client_id. Это скрыто, и значение извлекается из сегмента URL.
- другие поля являются динамическими (дата, тип, комментарии) и относятся к одному или нескольким продуктам, купленным этим клиентом.
Я не могу понять, как сохранить входные значения из динамических файлов в базу данных (извините, я совсем новичок в кодировании)
Смотрите ниже мой текущий код и попытки.
Я обнаружил, что связанные ответы в переполнении стека не могли привести их в соответствие с моим делом.
Буду признателен за помощь
STORE () ФУНКЦИЯ В КОНТРОЛЛЕРЕ
public function storeDYNarray(Request $request)
{
$client = $request->input('client_id');
$all = $request->input();
$products = $request->input('product');
//dd($all); SEE BELOW
//THIS CREATES AS MANY NEW ENTRIES IN PRODUCTS TABLE AS NEEDED WITH THE CORRESPONDING client_ID
foreach ($products as $product){
$dia = new Product;
//client_id is retrieved from an URL segment
$dia->client_id = $request->input('client_id');
//DON'T KNOW HOW TO SAVE VALUES FROM THE DYNAMIC FIELDS
$dia->save();
}
мой лучший снимок (много не стоит показывать)
public function storeDYNarray(Request $request)
{
$client = $request->input('client_id');
$all = $request->input();
$products = $request->input('product');
$i=1;
$client_products[$i] = array();
foreach ($products as $product){
while ($i<=count($products)){
$client_products[$i] = new Product(array(
'client_id' => $client,
'product_date' => $products[$i]['date'],
'product_type' => $products[$i]['type'],
'product_comment' => $products[$i]['comment'],
));
$client_products[$i]->save();
}
}
}
}
//this returns Undefined index errors
return dd ($ all); OUTPUT
array:3 [▼
"_token" => "uvtLaCiuAueBIuyWkoCoOTdQzYB1paxhnLw0lbyO"
"client_id" => "898"
"product" => array:2 [▼
1 => array:3 [▼
"date" => "2019-03-13"
"type" => "new"
"comment" => "surplus"
]
2 => array:3 [▼
"date" => "2019-03-28"
"type" => "used"
"comment" => "good condition"
]
]
]
ТАБЛИЦА ПРОДУКТОВ
class CreateProductsTable extends Migration
{
public function up()
{
//KEPT VALIDATION PARAMETERS SIMPLE FOR KNOW
Schema::create('products', function (Blueprint $table) {
$table->increments('product_id');
$table->string('client_id')->nullable($value = true);
$table->date('product_date')->nullable($value = true);
$table->string('product_type')->nullable($value = true);
$table->longText('comment_about_product')->nullable($value = true);
$table->timestamps();
});
}
МОДЕЛЬ ПРОДУКТА
class product extends Model
{
//GIVEN THE STRUCTURE OF ARRAYS WHEN dd($all); I DONT THINK I NEED THAT
/*
public $fillable = [
'client_id',
'product_date',
'product_type',
'product_comment',
];
*/
public function client(){
return $this->belongsTo('App\client');
}
}
ТАБЛИЦА КЛИЕНТА
<?php
//use Illuminate...
class CreateclientsTable extends Migration
{
public function up()
{
Schema::create('clients', function (Blueprint $table) {
$table->string('client_id');
$table->primary('client_id');
//other columns...
$table->integer('user_id')->nullable($value = true);
$table->timestamps();
});
}
МОДЕЛЬ КЛИЕНТА
class client extends Model
{
protected $primaryKey = 'client_id';
public $incrementing = false;
protected $keyType = 'string';
public function user(){
return $this->belongsTo('App\User');
}
public function products(){
return $this->hasMany('App\product');
}
}