I have a table and I want to update it, but theres always a problem everytime i update, it says its null or request column not found 0, someone can help me? Any idea?
Update controller
public function update(Request $request, string $id)
{
$invoice = Invoice::find($id);
$input = $request->all();
$invoice->update($input);
$title = $request->title;
$quantity = $request->quantity;
$unit_price = $request->unit_price;
$sort_order = $request->sort_order;
$invoiceDetails = [];
for ($i = 0; $i < count($title); $i++) {
$invoiceDetails[] = [
'sort_order' => $sort_order[$i],
'title' => $title[$i],
'quantity' => $quantity[$i],
'unit_price' => $unit_price[$i],
];
}
$invoice = $invoice->invoice_detail()->update($invoiceDetails);
return redirect('invoice')->with('flash_message', 'Updated');
}
Invoice model
class Invoice extends Model
{
use HasFactory;
protected $table = 'invoices';
protected $primaryKey = 'id';
protected $fillable = ['user', 'company', 'invoice_month'];
const UPDATED_AT = 'modified';
const CREATED_AT = 'created';
public function invoice_detail(){
return $this->hasMany(Invoice_detail::class, 'invoice_id');
}
}
Invoice detail model
class Invoice_detail extends Model
{
use HasFactory;
protected $table = 'invoice_details';
protected $primaryKey = 'id';
protected $fillable = ['title', 'quantity', 'unit_price', 'invoice_id'];
const UPDATED_AT = 'modified';
const CREATED_AT = 'created';
public function invoice(){
return $this->belongsTo(Invoice::class);
}
}
route
Route::get('invoice', [InvoiceController::class, 'index']);
Route::get('search', [InvoiceController::class, 'search']);
Route::resource('/invoic', InvoiceController::class);
I just want the right code to update in laravel, its in an array, cause my view is a bootstrap table
2
Answers
You are passing a multidimensional array so your keys are nested therefore considered missing.
Change your code to:
I am assuming based on your code that the variables you use to assign values to your keys are always present.
Maybe you should also consider some validation upon your request fields.
Updating the child records should not be done like this, update your code to this code because you haven’t any primary key ID of the child records. so first delete the child records and recreate them with updated records.