I have two models, one for Company and one for Invoice. There is a one-to-many relationship as the company can have many invoices.
I am now setting up the index page for the invoices, but in the index page, I want to display the company name. How can I set up the controller if I don’t yet have the ID for the company?
This is what I have so far on my invoice controller
public function index()
{
return Inertia::render('Invoices/Index', [
'invoices' => Invoice::all(),
]);
}
That passes all the invoices to the correct route, but I don’t know how to pass the company data.
My Invoice model looks like this – and the table has a company_id field
public function company(){
return $this->belongsTo(Company::class);
}
and my Company model looks like this
public function invoices(){
return $this->hasMany(Invoice::class);
}
The company migration is this
public function up()
{
Schema::create('companies', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('website')->nullable();
$table->string('address_1')->nullable();
$table->string('address_2')->nullable();
$table->string('city')->nullable();
$table->string('post_code')->nullable();
$table->string('country')->nullable();
$table->timestamps();
});
}
and the invoice migration is this
public function up()
{
Schema::create('invoices', function (Blueprint $table) {
$table->id()->from(8023052);
$table->integer('company_id')->unsigned();
$table->integer('invoice_company_id');
$table->text('description');
$table->string('status');
$table->decimal('subtotal', 8, 2);
$table->decimal('tax', 8, 2);
$table->decimal('total', 8, 2);
$table->date('invoice_date');
$table->date('due_date');
$table->timestamps();
});
}
2
Answers
thanks to LagBox and BlackLotus. I figured out how to do it. And in the end, my controller method looks like this now and it works perfectly.
Use eager loading,