2

I want to get 'loan_id' that was inserted in both tables.

With return $this->getConnection()->getPdo()->lastInsertId(); I suppose i should get at least last id (which is specified for this model as 'id' and autoincremented) but I don't receive it too. (just empty response)

Even better if I can get full object that was inserted in DB.

So, I wanted to catch an Exception if transaction fails and return error message in case of failure and $loan_id or saved Object in case of success. how to do it ?

<?php
namespace App\model;

use Illuminate\Database\Eloquent\Model as Eloquent;
//use Illuminate\Support\Facades\DB as DB;
use Illuminate\Support\Manager as Manager;
use Illuminate\Database\Capsule\Manager as DB;
use PDO;

class Loan extends Eloquent
{
    protected $table = 'loans';

    protected $primaryKey = 'id';

    public $timestamps = false;

    public function addLoan($amount, $instalments)
    {

        // Manager::connection()->getPdo()->beginTransaction();
        $this->getConnection()->transaction(function () use ($amount)
        {
            $loan_id = substr(uniqid(), -12);

            DB::table('loans')->insert([
                    'loan_id' => $loan_id,
                    'amount' => $amount,
                    'status' => 'requested'
                ]
            );

            DB::table('loan_instalment')->insert([
                    'loan_id' => $loan_id,
                    'principal' => 777.12,
                    'interest' => 333.12
                ]
            );

        });

        return $this->getConnection()->getPdo()->lastInsertId();
    }
}
?>
Nikita P
  • 149
  • 5
  • 19
  • you have two inserts. you'd only ever be able to get the id from `loan_instalment`, since last_insert() only ever returns ONE single id, from the last insert performed. – Marc B Aug 09 '16 at 14:53
  • yes, i understand that. But i don't get any Id – Nikita P Aug 09 '16 at 17:36

1 Answers1

2

Instead of

$this->getConnection()->getPdo()->lastInsertId()

You can do this:

DB::table('table')->insert([...])->lastInsertId();

And catching an exception see: Laravel: Using try...catch with DB::transaction()

Community
  • 1
  • 1
MDev
  • 176
  • 1
  • 1
  • 9