/** * UPDATE /api/favouritesTransactions/{favouriteTransactions} * @param Request $request * @param FavouriteTransaction $favourite * @return Response */ public function update(Request $request, FavouriteTransaction $favourite) { // Create an array with the new fields merged $data = array_compare($favourite->toArray(), $request->only(['name', 'type', 'description', 'merchant', 'total'])); $favourite->update($data); if ($request->has('account_id')) { $favourite->account()->associate(Account::findOrFail($request->get('account_id'))); $favourite->fromAccount()->dissociate(); $favourite->toAccount()->dissociate(); $favourite->save(); } if ($request->has('from_account_id')) { $favourite->fromAccount()->associate(Account::findOrFail($request->get('from_account_id'))); $favourite->account()->dissociate(); $favourite->save(); } if ($request->has('to_account_id')) { $favourite->toAccount()->associate(Account::findOrFail($request->get('to_account_id'))); $favourite->account()->dissociate(); $favourite->save(); } if ($request->has('budget_ids')) { $favourite->budgets()->sync($request->get('budget_ids')); } $favourite = $this->transform($this->createItem($favourite, new FavouriteTransactionTransformer()))['data']; return response($favourite, Response::HTTP_OK); }
/** * */ public function run() { $users = User::all(); foreach ($users as $user) { foreach ($this->favourites as $favourite) { $newFavourite = new FavouriteTransaction(['name' => $favourite['name'], 'type' => $favourite['type'], 'description' => $favourite['description'], 'merchant' => $favourite['merchant'], 'total' => $favourite['total']]); $newFavourite->user()->associate($user); if ($favourite['type'] === 'transfer') { $newFavourite->fromAccount()->associate(Account::where('user_id', $user->id)->where('name', $favourite['fromAccount'])->first()); $newFavourite->toAccount()->associate(Account::where('user_id', $user->id)->where('name', $favourite['toAccount'])->first()); } else { $newFavourite->account()->associate(Account::where('user_id', $user->id)->where('name', $favourite['account'])->first()); } $newFavourite->save(); $budgetIds = []; foreach ($favourite['budgets'] as $budgetName) { $budgetIds[] = Budget::where('user_id', $user->id)->where('name', $budgetName)->pluck('id'); } $newFavourite->budgets()->attach($budgetIds); } } }