How to make invoice in Laravel?

  invoice, laravel

I need your suggestions on how to make an invoice system in laravel. So far I created a temporary answer for it but Im not sure if my method of doing it is correct.

Here is my invoice migration

public function up()
    {
        Schema::create('invoices', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->integer('product_id')->unsigned();
            $table->date('invoice_date');
            $table->date('due_date');
            $table->foreign('product_id')->references('product_id')->on('products');
            $table->timestamps();
        });
    }

Here is my product migration

 public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->increments('product_id');
            $table->string('name');
            $table->integer('quantity');
            $table->integer('price');
            $table->timestamps();
        });
    }

Product Model

class Product extends Model
{
    public function invoices(){
        return $this->hasMany(Invoice::class);
    }
}

Invoice Model

public function product(){
        return $this->belongsTo(Product::class);
    }

Form

<form action="/insert" method="POST">
    @csrf

    <div class="form-group">
        Name: <input type="text" name="name">
    </div>
    <div class="form-group">
        Invoice Date: <input type="date" name="invoice_date">
    </div>
    <div class="form-group">
        Due Date: <input type="date" name="due_date">
    </div>
    <div class="form-group">
        Product Name: <input type="text" name="product_name">
        Quantity: <input type="text" name="quantity">
        Price: <input type="text" name="price">
    </div>

    <button type="submit">Insert</button>

</form>

Invoice Controller

public function invoice_create(Request $request){
        

        $product = new Product;
        $product->name = $request->input('product_name');
        $product->quantity = $request->input('quantity');
        $product->price = $request->input('price');
        $product->save();

        $invoice = new Invoice;
        $invoice->name = $request->input('name');
        $invoice->invoice_date = $request->input('invoice_date');
        $invoice->due_date = $request->input('due_date');
        
        $product = $product->invoices()->save($invoice);
        return redirect('/create');
    
    }

It would be really appreciated if you could suggest what other inputs are needed. But right now my primary focus is that if my method of doing it is correct or not. Thanks for the reply

Source: Laravel

Leave a Reply