Created
February 7, 2020 03:40
-
-
Save ikarius6/d793208b851f9583b5d858e9f22b265f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Model: Expense.php | |
<?php | |
namespace App; | |
use Illuminate\Database\Eloquent\Model; | |
class Expense extends Model | |
{ | |
protected $fillable = [ | |
'source_id', 'expense_category_id', 'quantity', 'note' | |
]; | |
//... | |
public function source() | |
{ | |
return $this->belongsTo(Source::class); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Controller: ExpenseController.php | |
<?php | |
namespace App\Http\Controllers; | |
use App\Expense; | |
use App\Http\Requests\ExpenseRequest; | |
use Illuminate\Http\Request; | |
use Illuminate\Support\Facades\Auth; | |
use Illuminate\Support\Facades\DB; | |
class ExpenseController extends Controller | |
{ | |
//... | |
public function store(ExpenseRequest $request) | |
{ | |
DB::beginTransaction(); | |
try { | |
$expense = new Expense($request->all()); | |
Auth::user()->expenses()->save($expense); | |
$expense->source->subExpense($expense); | |
DB::commit(); | |
} catch (\Exception $e) { | |
DB::rollback(); | |
return response()->json(['message' => $e->getMessage()], 500); | |
} | |
return response()->json($expense, 201); | |
} | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Model: Source.php | |
<?php | |
namespace App; | |
use Illuminate\Database\Eloquent\Model; | |
class Source extends Model | |
{ | |
protected $fillable = [ | |
'name', 'quantity' | |
]; | |
//... | |
public function expenses() | |
{ | |
return $this->hasMany(Expense::class); | |
} | |
public function subExpense($expense) { | |
$this->quantity = $this->quantity - $expense->quantity; | |
$this->save(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Algo así debería quedar pero en expense
//Expense model
public function subExpense($expense) {
$this>quantity-=$this->source()->quantity// puedes acceder al source por medio del belongsTo ya que es
parte del mismo modelo
}