I am trying to save multiple data which is having a many-to-many relationship. My store method is like the below.
public function store(Specification $specification, Fraction $fraction, Request $request)
{
$data = return request()->validate([
'specification_no' => 'required|string',
'grade' => 'required|integer',
'gname' => 'required|integer',
'gsize' => 'required|integer',
'fractions.*.fraction_min' => 'required',
'fractions.*.fraction_max' => 'required',
'fractions.*.unit_id' => 'required',
'fraction_sieves.*.sieve_id' => 'required',
'params.*.para_min' => 'required',
'params.*.para_max' => 'required',
'units.*.unit_id' => 'required',
]);
// Save specificatio without duplicates.
$specification = new Specification($this->specificationValidation());
$checkSpecification = Specification::where('specification_no', request()->specification_no)->first();
if (!$checkSpecification) {
$specification->save();
$specification->grades()->syncWithoutDetaching($data['grade']);
$specification->gnames()->syncWithoutDetaching($data['gname']);
$specification->gsizes()->syncWithoutDetaching($data['gsize']);
$specification->sieves()->syncWithoutDetaching($data['fraction_sieves']);
// $specification->load('sieves.fractions');
$fraction = $specification->sieves()->fractions()->createMany($data['fractions']);
dd($fraction);
}
return redirect()->back()->with('alert', 'Duplicate Specification number.');
}
Models & migrations like below.
Fraction-Model
class Fraction extends Model{
protected $guarded = [];
public function sieves()
{
return $this->belongsToMany(Sieve::class);
}
}
migration - fraction
public function up(){
Schema::create('fractions', function (Blueprint $table) {
$table->bigIncrements('id');
$table->double('fraction_min');
$table->double('fraction_max');
$table->unsignedBigInteger('unit_id');
$table->timestamps();
});
}
model - sieve
class Sieve extends Model{
protected $guarded = [];
public function specifications(){
return $this->belongsToMany(Specification::class);
}
public function fractions(){
return $this->belongsToMany(Fraction::class);
}
}
migration pivot table - fraction_sieve
public function up()
{
Schema::create('fraction_sieve', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('sieve_id');
$table->unsignedBigInteger('fraction_id');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('fraction_sieve');
}
When I use the below code
$fraction = $specification->sieves()->fractions()->createMany($data['fractions']);
to save fractions to fractions table with distance relationships from specifications->sieves->fractions, I am getting errors like this.
BadMethodCallException Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsToMany::fractions()
Normally this could be the way of creating new multiple data into db. But I can not understand why I'm getting errors. Can someone explain what I've messed up?