I have a table for the invoice and it has the primary key which is id, and for invoice details the foreign key is invoice_id. What I want is during saving the primary key on the invoice, it would also save the primary key on the foreign key of invoice details, at the same time.
Heres my code for the store:
public function store(Request $request)
{
$validation = $request->validate([
'user' => 'required',
'company' => 'required',
'invoice_month' => 'required',
]);
Invoice::create($validation);
$title = $request->title;
$quantity = $request->quantity;
$unit_price = $request->unit_price;
$sort_order = $request->sort_order;
$now = Carbon::now();
for($i=0; $i < count($title); $i++){
$datasave = [
'sort_order' => $sort_order[$i],
'title' => $title[$i],
'quantity' => $quantity[$i],
'unit_price' => $unit_price[$i],
'created' => $now,
'modified' => $now,
];
DB::table('invoice_details')->insert($datasave);
}
return redirect('invoice')->with('flash_message', 'Saved');
}
for the models:
<?php
namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
class Invoice_detail extends Model
{
use HasFactory;
protected $table = 'invoice_details';
protected $primaryKey = 'id';
protected $fillable = ['title', 'quantity', 'unit_price'];
public function invoice(){
return $this->belongsTo(AppInvoice::class, 'invoice_id');
}
}
<?php
namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
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->hasOne(AppInvoice_detail::class);
}
}
for the route
Route::get('/home', function(){
return view('homepage');
});
//Route::resource('invoice', InvoiceController::class);
Route::get('invoice', [InvoiceController::class, 'index']);
Route::get('search', [InvoiceController::class, 'search']);
Route::resource('/invoic', InvoiceController::class);
Any help or idea, i will appreciate it. What I want to happen, when you are entering all of the fields, the primary key will also saved on the foreign key of the invoice details.
2
Answers
Khayam Khan, do i add it here? this code?
$invoice = Invoice::with('invoice_detail')->findOrFail($invoice_id); Theres an error , $invoice_id undefined.
public function index() {
you can has many invoice details and you have written one relationship and you are saving many records.
on the other hand, you can use relationships to save the related data or can do it manually.
change you relationship first in the invoice model.
then in the Invoice_detail also provide invoice_id in the fillable array.
then you can do this to save related data.
now if you want to fetch the data, you fetch it very easily like below,
then in the blade or anywhere for example blade,