Reputation: 114
I've been searching endlessly for a clue on how I should properly go about creating a "Money Transfer" function (for a game, not real money) within Laravel 4.2.
Needlessly to say, I've come up empty handed and I'm turning to you guys.
The task:
What I need:
Database:
id, user_id, spending, saving, bucks, pin, created_at, updated_at
Model:
class Bank extends Eloquent {
protected $table = 'banks';
protected $fillable = ['user_id, spending, saving, bucks, pin'];
// Connect to the User
public function user()
{
return $this->belongsTo('User');
}
}
Controller:
public function transferMoney()
{
$id = Auth::id();
$bank = Bank::find($id);
$spending = $bank->spending;
$saving = $bank->saving;
$transfer_type = Input::get('transfer_to');
$transfer_amount = Input::get('amount');
// Spending to Savings
if($transfer_type = 1) {
if($transfer_amount >= $spending) {
// the magic to transfer the funds goes here.
}
}
// Savings to Spending
if($transfer_type = 2) {
if($transfer_amount >= $savings) {
// the magic to transfer the funds goes here.
}
}
}
Form in View:
{{ Form::open(array('route' => array('transferMoney'), 'method' => 'post')) }}
{{ Form::select('transfer_to', array('1' => 'Spending to Saving', '2' => 'Saving to Spending')) }}
{{ Form::text('amount', null, ['placeholder' => 'Amount']) }}
{{ Form::submit('Transfer', array('class' => 'button secondary pull-right')) }}
{{ Form::close() }}
Route:
Route::post('/bank', array('as' => 'transferMoney', 'uses' => 'BankController@transferMoney'));
Any tips & tricks on best practices are hugely appreciated! Apologies if this repeated - I swear I can't find a solution to this specific roadblock.
Thank you!
Upvotes: 0
Views: 36
Reputation: 764
I believe you'll need to subtract the amount ($transfer_amount
) from the transfer-er and add it to the transfer-ee
public function transferMoney()
{
$id = Auth::id();
$bank = Bank::find($id);
$transfer_type = Input::get('transfer_to');
$transfer_amount = Input::get('amount');
// Spending to Savings
if($transfer_type == 1)
{
if($transfer_amount > $bank->spending)
{
// Error - insufficient funds
}
else
{
$bank->spending -= $amount;
$bank->saving += $amount;
$bank->save();
}
}
// Savings to Spending
if($transfer_type == 2)
{
if($transfer_amount > $bank->saving)
{
// Error - insufficient funds
}
else
{
$bank->spending += $amount;
$bank->saving -= $amount;
$bank->save();
}
}
}
I also fixed a few syntactical things (if($transfer_type = 1)
needs more than one =
).
Make sure you validate that the transfer amount is a valid number! :)
Upvotes: 1