Model::Create() method not inserting with InnoDB storage engine

I am trying to insert a new record customer into MySQL database as following:

$customer = Customer::create(['name'=>$request->customerName,
'email'=>$request->customerEmail,
'phone'=>$request->customerPhone,
'area_id'=>$request->customerArea,
'gender'=>$request->customerGender]);
dd($customer->id);

It works well with myISAM storage engine and a new record is there, but not working with InnoDB, the post request returns 200 with no record in the database. While the dump dd() returns the new ID as it’s auto incremented. The ID is taken already, as when I insert a new record it gives me a newer ID than previous one, with no record in the database also.

Model::Create() method not inserting with InnoDB storage engine

Model::Create() method not inserting with InnoDB storage engine

Here’s Customer model structure:

namespace AppModelsUser;

use IlluminateDatabaseEloquentModel;

class Customer extends Model
{
    protected $fillable = [
        'name', 'phone', 'email', 'area_id', 'gender'
    ];

    protected $table = 'customers';
}

And here’s customers table structure:

Model::Create() method not inserting with InnoDB storage engine

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

When using InnoDB, you need to know at least a little about “transactions”.

If you have autocommit=ON, each statement (such as INSERT) will be a transaction unto itself and will be automatically COMMITTed.

If you have autocommit=OFF, you must eventually issue COMMIT. This is because the statements (INSERTs, etc) are being collected in a “transaction”.

The latter case fits the symptoms.

Method 2

Since you have created your Customer model, why don’t you use it directly like this :

$customer = new Customer();
$customer->name = $request->customerName;
$customer->email = $request->customerEmail;
$customer->phone = $request->customerPhone;
$customer->area_id = $request->customerArea;
$customer->gender = $request->customerGender;
$customer->save();

PS. Don’t forget, of course, to import your Customer model into your controller


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x