in my database i have product_category
and products
that one product
maybe belongs to one or some category in product_category
table, now my question is: when user on submitting product with one or some category how can i save that on database to have for example one category have one or some product?
in view i have multiple select as:
{{ Form::select('categories[]', $productCategories, null, array('class' => 'multiselect-success multiselect_selected','multiple'=>'multiple')) }}
products
model:
class Products extends Model
{
protected $table = 'products';
protected $guarded = ['id'];
protected $casts = [
'images' => 'array'
];
public function productCategories()
{
return $this->belongsTo(ProductCategories::class);
}
}
productCategories
model:
class ProductCategories extends Model
{
protected $table = 'product_categories';
protected $guarded =['id'];
protected $casts=[
'images'=>'array'
];
public function products()
{
return $this->hasMany(Products::class);
}
}
and store
function into controller
:
public function store(RequestProducts $request)
{
try {
$data = Products::create([
'name' => $request->name,
'amount' => $request->amount,
'product_code' => $request->product_code,
'weight' => $request->weight
/* MY PROBLEM IS HERE */
'category_id' => $request->categories
]);
} catch (Exception $ex) {
...
}
return redirect(route('manageProductCategories.index'));
}
in html view categories
is an array and how can i implementing that?
UPDATE
after update code with createMany
i get this error:
General error: 1364 Field 'category_id' doesn't have a default value (SQL: insert into `products` (`name`, `lang`, `amount`, `product_code`, `weight`, `images`, `updated_at`, `created_at`) values (eqweqwe, fa, 45,000, asd, asdasd, '', 2017-12-09 04:45:44, 2017-12-09 04:45:44))
migration files:
public function up()
{
Schema::create('product_categories', function (Blueprint $table) {
$table->increments('id');
$table->string('category_name');
$table->string('lang', 2);
$table->text('images');
$table->timestamps();
});
}
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('amount');
$table->string('product_code');
$table->string('weight');
$table->string('lang', 2);
$table->text('images');
$table->integer('category_id')->unsigned()->index();
$table->foreign('category_id')->references('id')->on('product_categories')->onDelete('cascade');
$table->timestamps();
});
}
From your question and comments, I understand the following.
Many products may have the category "category_1" and "product_1" may belongs to many categories.
To implement this you have to use "Many To Many" relationship. I have updated your code, this might help you.
Migrations:
Models
products model:
productCategories model:
Controller
Hope it will helps..