2

I'm trying to make a simple function that will charge cashback for purchases on the site. The principle is as follows: I have a buy table, where all purchase operations are indicated, and in this table there are 3 required columns: user_id, bank and status. Bank - transaction amount, status - transaction status, user_id - ID at users table. If status is 2, then the purchase has been paid. I take all the data from the buy table, get it with status = 2, and then I need to enter to the users table, find the user ID there by user_id from the buy table, see the amount of his purchase where status is 2, and if everything is fine, I need to add 1 % cashback of the purchase amount.

I'm trying to do it all with this function:

public function cashbackUser()
{
    $find_user = DB::table('buy')->where('status', 2)->get();
    $users = DB::table('users')->get();
    foreach ($users as $addCashback) {
        $addCashback->cashback = $addCashback->cashback + $find_user->bank / 100 * 1;
        $addCashback->save();
    }
}

But i received error: Property [bank] does not exist on this collection instance.. How i understand, it can't find the all summs from bank at buy table, because i can't to use ->get()? What i need to change and get work it?

yrbet
  • 191
  • 2
  • 10
  • 3
    `$find_user` is a collection. If you only need one element, use `first()` instead of `get()`. If you expect more than one, you'll have to loop over it like you do with `$users`, and determine, based on your business logic, how to join up `$find_user` and `$users`. – miken32 Dec 16 '20 at 18:05
  • yes, i need to all elements – yrbet Dec 16 '20 at 18:11
  • Do you want to add 1% of all the purchases combined ? – Umer Abbas Dec 16 '20 at 18:20
  • yes, to all sucess puchased with `status = 2` – yrbet Dec 16 '20 at 18:21
  • Post another question so I can provide solution, this question is already closed. – Umer Abbas Dec 16 '20 at 18:36
  • can post only once in 90 minutes :( maybe you can write solution for example in pastebin.com? – yrbet Dec 16 '20 at 18:38
  • `public function cashbackUser() { $users = DB::table('users')->get(); foreach ($users as $addCashback) { //assuming the primary key in users table is id $total_purchase = DB::table('buy')->where('user_id', $addCashback['id'])->where('status', 2)->sum('bank'); //one percent of total purchase is calculated like (1/100)*total_purchase $addCashback->cashback = $addCashback->cashback + ((1/100)*$total_purchase); $addCashback->save(); } }` – Umer Abbas Dec 16 '20 at 18:39
  • just copy past this into your editor and try it – Umer Abbas Dec 16 '20 at 18:40
  • received: `Cannot use object of type stdClass as array` – yrbet Dec 16 '20 at 18:44
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/226058/discussion-between-omar-abbas-and-yrbet). – Umer Abbas Dec 16 '20 at 18:45

0 Answers0