I am facing very odd behavior of Laravel 5.2 Eloquent. When I try to insert a row in my table it returns an object which have incremented ID. Now the issue is, the ID it return is not the ID of that row.
eg
My Code:
DB::beginTransaction();
//create a new product
$product_p = new Product();
$product_p->name = $request->name;
$product_p->barcode = $request->barcode;
$product_p->sale_price = $request->sale_price;
$product_p->save();
echo $product_p->id; //this gives invalid ID
DB::commit();
When I try to access $product_p->id
it returns 31 even though the product id in the database is 5.
I have developed sync controller which is responsible to make record of every query executed, ON further investigation I found the sync controller id is responsible for invalid ID.
My Route File
// SyncController
\Event::listen('Illuminate\Database\Events\QueryExecuted', function ($query) {
$sync = new \App\Http\Controllers\SyncController();
$sync->addOperation($query->sql, $query->bindings);
});
My Sync Controller
DB::beginTransaction();
$sync = New Sync();
$sync->action = $sql;
$sync->data = json_encode($data);
$sync->save();
DB::commit();
My DB Structure for product
id Primary int(10) UNSIGNED AUTO_INCREMENT
name varchar(255)
barcode int(11)
sale_price int(11)
This is my Product Migration
Schema::create('products', function(Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('barcode')->unique();
$table->integer('sale_price');
$table->timestamps();
});
Try this at store method in Controller.
$input_data = $request->all();
$last_inserted_data = YourModelName::create($input_data);
dd($last_inserted_data)
Check the output from dd()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.