I had two similar fields namely total_weight that is in my phyto table and weight that is in my phyto_species table shown below
CreatePhytosTable
public function up() { Schema::create('phytos', function (Blueprint $table) { $table->id(); $table->string('customer_name'); $table->string('phyto_number'); $table->decimal('total_weight'); $table->date('date_send'); $table->softdeletes(); $table->timestamps(); }); }
CreatePhytoSpeciesTable
public function up() { Schema::create('phyto_species', function (Blueprint $table) { $table->id(); $table->integer('phyto_id')->unsigned(); $table->integer('species_id')->unsigned(); $table->integer('destination_id')->unsigned(); $table->integer('preservation_id')->unsigned(); $table->double('weight', 8,2); $table->softdeletes(); $table->timestamps(); }); }
I have been trying to sum weight using array_sum() as total weight and then assign it to ‘total_weight’ => $totalweight] shown below however when I save the error says Undefined variable: totalweight. I would like to request for assistance please
public function store(CreatePhytoRequest $request) { $phyto = $this->phytoRepository->create( ['customer_name' => $request->customer_name, 'phyto_number' => $request->phyto_number, 'date_send' => $request->date_send, 'total_weight' => $totalweight] ); $species = $request->input('species_id', []); $weight = $request->input('weight', []); $destination = $request->input('destination_id', []); $preservation = $request->input('preservation_id', []); for ($i=0; $i < count($species); $i++) { if ($species[$i] != '') { $phyto->species()->attach($species[$i], ['weight' => $weight[$i],'destination_id' => $destination[$i],'preservation_id' => $preservation[$i]]); } } //array_sum work fine $totalweight = array_sum($weight); Flash::success('Phyto saved successfully.'); return redirect(route('consignment.phytos.index')); }
Advertisement
Answer
declare the variable
$totalweight = array_sum($weight);
before you call it. Your code should be something like:
public function store(CreatePhytoRequest $request) { //Get everything from requests $weight = $request->input('weight', []); ... // Declare needed variables $totalweight = array_sum($weight); $phyto = $this->phytoRepository->create( ['customer_name' => $request->customer_name, 'phyto_number' => $request->phyto_number, 'date_send' => $request->date_send, 'total_weight' => $totalweight]); ... // and so one }