Toby Nwude
Toby Nwude

Reputation: 411

How to query two tables in Laravel

I am trying to query two tables in Laravel when the user submits a form. The data is stored in the transaction table and I can also update the Account table by adding the $transactions->amt with $account->total.

I tried doing this;

public function store(Request $request)
    {
        $account = DB::table('users')
            ->join('accounts', "users.id", '=', 'accounts.user_id')
            ->select('users.*', 'accounts.*')
            ->first();

        $transaction = new Transaction();
        $data  = $this->validate($request, [
            'baddress'=>'required',
            'package'=>'required',
            'amt'=>'required',
        ]);
        $transaction->username = $account->username;          
        $transaction->baddress = $request->input('baddress');
        $transaction->package = $request->input('package');
        $transaction->amt = $request->input('amt');
        $transaction->fund_option = "Fund";
        $transaction->save();

        $bal= $transaction->amt + $account->total;

        $account->amt_paid = $bal;
        $account->total = $bal;
        $account->save();

        return redirect('/transfer')->with('success', 'Transaction has been made');
    }

but I got this error:

Call to undefined method stdClass::save()

How can I find the best method to do this?

Upvotes: 0

Views: 78

Answers (3)

dikutandi
dikutandi

Reputation: 127

That error occur because $account is not collection. method save() is method from model collection.

if you want update you can use this code like.

$accountUpdate = DB::table('accounts')
          ->where('id', $account->id)
          ->update(['amt_paid' => $bal, 'total' => $bal]);

but if you want to use method save() then you have to call $account from model.

Upvotes: 1

A.A Noman
A.A Noman

Reputation: 5270

You have to use like this. This is simple as like as much

$accountModelUpdate = DB::table('accounts')
      ->where('user_id', $account->id)
      ->update(['amt_paid' => $bal, 'total' => $bal]);

Upvotes: 1

fabio.ivona
fabio.ivona

Reputation: 618

$account is a row made by your join (users.* and accounts.*) so it's a stdClass, not an Eloquent model. You don't have a save() method

in order to do this you should have a relationship between User model and Account model:

//Account.php

public function user(){
     return $this->belongsTo("App\User");
}

........

//User.php

public function account(){
     return $this->hasOne("App\Account");
}

then you can retrieve Account from your User:

$user = User::first();

$account = $user->account;

[....]

$account->amt_paid = $bal;
$account->total = $bal;
$account->save();

Upvotes: 1

Related Questions