How to show bank balance through transactions in laravel - laravel

I have Bank table and transaction table. The relationship is one-to-many, so a bank may have many transactions. Transaction table has the bank foreign key(bank_id). and each transaction has a column 'type' which is either credit or debit.
I want to show each bank balance based on its transactions.
Here are my questions:
How to select a specific bank?
How to calculate the balance for a bank?
Should I calculate it in controller, model, or view? which one is the best?
Here is transactions table:
thanks in advance!

I'm not sure what you are trying to do. You'd select a bank like
$bank = Bank::find(2);
and you could do something like
$bank->transactions->sum('amount');

You need to create relationships in the model, like this in the Transactions model:
public function bank(){
return $this->belongsTo(Bank::class);
}
and this in the Bank Model
public function transactions (){
return $this->hasMany(Transactions::class);
}
Then you can access them like this:
$this->bank->transactions;
Laravel has excellent docs, you just need to read them, e.g. Relationships

I wanted to show the balance of each bank in my database. I had to sum all credits which belongs to a bank and then sum all debits for that bank and then find the balance, which is credits minus debits. So using relationship you mentioned. I wrote this code.
<td>{{$bank->transactions->where('type', 'credit')->sum('amount') - $bank->transactions->where('type', 'debit')->sum('amount')}}</td>

Related

Laravel models, database and pivot tables question

Hello I am working with Laravel,
I have to create two simple models, let's say Stores and Books.
Stores can have one or multiple Books and Books can belong to many Stores.
Of course I will use a many to many relationship, with a pivot table.
Books the can have different prices depending the store.
I think a separate table can only complicate things, in my mind the pivot table associating books and stores should have a price column, but pivot tables only contains store_id and book_id.
Should I create a book_prices and associate it with books and to stores? What is the best approach?
You are free and able to set other attributes on your pivot table. You can read more about it in the docs.
https://laravel.com/docs/9.x/eloquent-relationships#retrieving-intermediate-table-columns
You have to define the relationship accordingly, the following should clarify how this works. In this example you use the many-to-many relationship and add the price column to every retrieved pivot model.
public function books()
{
return $this->belongsToMany(Book::class)
->withPivot('price')
}
For example, you are able to access the pivot column in a loop like this
foreach ($shop->books as $book)
{
echo $book->pivot->price;
}
You can define additional columns for your pivot table in the migration for the pivot table, and then when defining the relationship use withPivot to define the additional columns so they come through in the model:
return $this->belongsToMany(Book::class)->withPivot('price');
(Adapted from the Laravel documentation, see https://laravel.com/docs/9.x/eloquent-relationships#retrieving-intermediate-table-columns)
Depends on the complexity of your case, but yes, you have two options for it. Let's say that the pivot table is called as book_store:
Directly adds price column to book_store. This is obviously the simpler option. The drawbacks are:
The history of the price changes isn't logged. You'll have to create another table for logging if you want to keep this history information.
Changes made to price will directly change the price of the related book_store record. Meaning that a price is being updated "live" e.g users cannot update the price now but "publish" it some time later just like this example in the doc.
Create a new, different table to store the price. This may seems relatively more complex, but it may also be more future-proof.
Basically, you get 2 things that you miss in the first option above.
Don't think too much about book_store being a pivot table. One way to see it is like this: book_store IS a pivot table from books and stores tables viewpoints, but it's also just a normal SQL table which could relate to any other tables using any kind of relationships.
If you want to implement this, make sure to create a primary-key in the book_store table.
Alast, it all depends on what you need. Feel free to ask if you need more insight about this. I hope this helps.

How display model with four relationships based on date in laravel?

I have these models:
Partner
Invoice
Bill
Transaction
CreditNote
Invoice, Bill, Transaction, and CreditNote belong to Partner.
and Partner has many invoices, bills, transactions, credit_notes.
I want to make SOA reports, which are based on date.
for example:
DATE TYPE ITEM
2021-1-1 partner invoiced us invoice_number..
2021-1-2 us invoiced partner bill_number..
2021-1-3 partner paid us transaction_debit
2021-1-4 us paid partner transaction_credit
2021-1-5 partner paid us credit_note
I use `rappasoft livewire data table to show this information.
I get partner stuff like this:
Partner::where('id', 1)->with('invoices', 'bills', 'transactions', 'credit_notes')->get()
I don't know how to display these information in a table a sort based on date
How to do this?
It sounds to me like your structure is wrong. All of the five things that you're putting in your table are what I'd consider "transactions" (not to be confused with your model "Transactions".
That being the case, then you want either want a Transactions model which is morphable (that's the more complicated solution) or which has a "type" property.
If morphable, each transaction would then be associated to the corresponding partner, and to the corresponding model - invoice, bill, payment, refund, etc. - on a "morphsTo" basis.
If you went down the easier route, each transaction would just have a type, linked to a TransactionType model, which would indicate the type of the transaction.
As things stand, your structure is overcomplicated. Either of the above approaches would simplify it.

Inverse of belongsToMany

I got two Models:
Order
Invoice
Each Order can have many Invoices - and an Invoice can belong to many Orders.
So I can search for an Order and check: "Hey, which Invoices have been created for this Order?"
The other way round each Invoice can belong to multiple Orders, because maybe a customer ordered two products on the same day and so it would be great he'd only get one Invoice, which includes both orders.
So this is how I did this:
Invoice
public function orders()
{
return $this->belongsToMany(Order::class);
}
Order
public function invoices()
{
return $this->belongsToMany(Invoice::class, 'invoice_order');
}
This does work - but it does not seem right to change the table to the intermediate table invoice_order here. Do you have any thoughts on this? :-)
Thanks in advance for your thoughts :-)
Seperating the relation into a seperate pivot table is the commonly used method in laravel (and in most other frameworks) for many to many relationships.
It's easy to maintain, easy to get related models using many to many relationship, and if someone else needs to work on it in the future, they'll probably have used it in the past as well so wouldn't end up burning their heads.
The other method you could use is to create a json column on one of the tables (you can create on both tables as well if you want, but that's just extra overhead). Then you can store the ids of the related models in this json column. You can then join the tables using the json related commands provided by your database. Eloquent does not support relationships on json, but you can use this package staudenmeir/eloquent-json-relations to build relationships on json fields.
So overall, I'd suggest keeping a pivot table like the standard way, but if that just won't do, then you can try the json column method

laravel - how to set relation with hasManyThrough?

I have problem with relation of laravel in this case.
One event has many event dates.
One event date has many tickets.
One ticket has many slots. User will book slot and save in booking table.
How can i get list of event dates have list of tickets and total booking of every ticket ?
In Event model i has :
return $this->hasMany('App\EventTicket', 'event_date_id');
Please help me improve it to get right data ?
1) How can I get list of event dates to have list of tickets?
you can make hasManyThrough relation for that. In EventDates model make relation as tickes with hasManyThrough.
Now through event dates, you will get all the tickets for that day.
2) total booking of every ticket
after make hasManyThrough you can use withCount('tickes') with this, you'll get the booking total count.

How to create a pivot table with related field other than id on Laravel 5.2

I want to create (on Laravel 5.2) a pivot between two entities, let's assume that we have the entities User and Phone. In our world, a user can have several phones, and te phones can have several owners.
For a reason, I must target the user's phone by it's serial number and the build year (let's assume that serials can't be identical on a same year).
So I have my tables users, phones andusers_phones.
===== Table users =====
id
username
...
===== Table phones ====
id
serial_numer
build_year
===== Table users_phones ====
user_id
phone_serial
phone_build_year
I have my relation on my model Phone :
public function users()
{
return $this->belongsToMany(
User::class,
'users_phones',
'user_id',
'phone_serial'
)->withPivot('phone_build_year');
}
When I wan't to add some entries like that :
$phone->users()->attach([$user->id => [
'phone_build_year' => $phone->build_year
]]);
The SQL request generated is the following one :
insert into `users_phones` (`user_id`, `phone_serial`, `phone_build_year`) values (1, 5, 2016)
My problem is that the 5 in the sql request is the phone id and not its serial. I didn't find how to precise to Laravel to use the field we chose (here the serial) rather than the id.
Is it possible to do that, or am I condemned to create a model to manipulate my special pivot table ? I admit that I would appreciate if I could avoid that way.
So, as Jarek says, it seems that there is no way to customize the Laravel pivot relations as I would like to do. I will create a model dedicated to this particular case.
Anyway, if someone has a better and elegant way to do this kind of custom pivot relation on Laravel, please share your knowledge !

Resources