我一直在无休止地寻找关于如何正确地创建一个" Money Transfer" Laravel 4.2中的功能(对于游戏,而不是真钱)。
不用说,我空手而归,我转向你们。
任务:
我需要什么:
数据库:
id, user_id, spending, saving, bucks, pin, created_at, updated_at
型号:
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');
}
}
控制器:
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::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::post('/bank', array('as' => 'transferMoney', 'uses' => 'BankController@transferMoney'));
任何提示&我们非常感谢最佳实践的诀窍! 如果重复这一点,我深表抱歉 - 我发誓我无法找到解决这一特定障碍的方法。
谢谢!
答案 0 :(得分:1)
我相信您需要从转帐人中减去金额($transfer_amount
)并将其添加到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();
}
}
}
我还解决了一些语法问题(if($transfer_type = 1)
需要不止一个=
)。
确保您确认转帐金额是有效号码! :)