Get the Last Inserted Id Using Laravel Eloquent
After save, $data->id
should be the last id inserted.
$data->save();
$data->id;
Can be used like this. return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);
For updated laravel version try thisreturn response()->json(array('success' => true, 'last_insert_id' => $data->id), 200);
How to get last insert id in Eloquent ORM laravel
Like the docs say: Insert, update, delete
"You may also use the create method to save a new model in a single
line. The inserted model instance will be returned to you from the
method. However, before doing so, you will need to specify either a
fillable or guarded attribute on the model, as all Eloquent models
protect against mass-assignment.After saving or creating a new model that uses auto-incrementing IDs,
you may retrieve the ID by accessing the object's id attribute:"
$insertedId = $user->id;
So in your sample:$user = User::create($loginuserdata);
$insertedId = $user->id;
then on table2 it is going to be$input['table2_id'] = $insertedId;
table2::create($input);
How to get last inserted id in Laravel?
Use insertGetId()
$id = DB::table('users')-> insertGetId(array(
'email_id' => $email_id,
'name' => $name,
));
laravel 8 : insert method get last insert id in eloquent (İnsert Method)
$insert = Product::create($alldata);
$insert->id
Holds the id of the inserted item.Basically you have the whole collection in your $insert
variable, of the item that you inserted.
How to get last id inserted on a database in Laravel?
4 Ways to Get Last Inserted Id in Laravel :
Using insertGetId()
method:
$id = DB::table('users')->insertGetId(
[ 'name' => 'first' ]
);
Using lastInsertId()
method:DB::table('users')->insert([
'name' => 'TestName'
]);
$id = DB::getPdo()->lastInsertId();
Using create()
method:$data = User::create(['name'=>'first']);
$data->id; // Get data id
Using save()
method:$data = new User;
$data->name = 'Test';
$data->save();
dd($data->id);
Get the id of the stored items after using Laravel insert eloquent
For bulk insertion there's no built in method to get inserted IDs. You can use foreach loop to insert one by one and get the IDs using insertGetId
and put them into an array.
$insertedIDs = [];
if (count($newTags) > 0) {
foreach ($newTags as $newTag) {
$insertedIDs[] = Tag::insertGetId($newTag);
}
}
How to get last inserted non incremental id using eloquent in Laravel?
This is because you are assigning request values to your customer variable.
$customer=new Customer;
$customer=$request->name;
$customer=$request->type;
$customer=$request->dob;
$customer->save();
When you are calling save()
, you are actually calling save()
on a string. Fix it by specifying the fillable properties on your
Customer
model. This is just an example.$customer = new Customer();
$customer->name = $request->name;
$customer->type = $request->type;
$customer->dob = $request->dob;
$customer->save();
After that, $customer->customer_id
should not be null.Edit: Failed to notice the following line:
public $incrementing = false;
which means at the time of creating your Customer
you would also have to supply the customer_id
, since it is no longer auto-incrementing. I also took a deeper look at the API. It seems Laravel won't be aware of the attribute set by the trigger at that stage. You can try to refresh()
the model which will pull in fresh attributes from the DB and assuming your triggers are working fine, you should be getting back a customer_id
.
So essentially, just add this line before adding the Delivery Address.
$customer->refresh();
I also noticed you don't have any logic to redirect the user back on successful save.I suspect this is why it is throwing the 404 since the same route isn't defined for a
GET
request. public function store(Request $request)
{
$customer = new Customer;
$invoiceAddress = new Address;
$deliveryAddress = new Address;
$customer->name = $request->name;
$customer->type = $request->type;
$customer->dob = $request->dob;
$customer->country_code = $request->country_code;
$customer->save();
$customer->refresh();
$deliveryAddress->street_name_no = $request->street_name_no;
$deliveryAddress->city = $request->city;
$deliveryAddress->country = $request->country;
$deliveryAddress->customer_id = $customer->customer_id;
$deliveryAddress->save();
return back()->with('success', 'Success message here');
}
Edited again: It seems from the doc, the refresh()
method is as follows:
/**
* Reload the current model instance with fresh attributes from the database.
*
* @return $this
*/
public function refresh()
{
if (! $this->exists) {
return $this;
}
$this->setRawAttributes(
static::newQueryWithoutScopes()->findOrFail($this->getKey())->attributes
);
$this->load(collect($this->relations)->except('pivot')->keys()->toArray());
$this->syncOriginal();
return $this;
}
As you can see from the following line:static::newQueryWithoutScopes()->findOrFail($this->getKey())->attributes
It will try to find or fail (404) while refreshing the model. I suspect in this case, that it is not able to get the appropriate key and that is why it is failing. I think in this particular case, you will have to get the customer_id
from the sequence_customers
table. Maybe you could get away by doing something like the following:
// Assuming SequenceCustomer is the model name
$latest = \App\SequenceCustomer::latest()->first();
// and then you would be able to access the latest customer_id by doing the following
$customer_id = $latest->customer_id;
This is obviously not a scalable solution, but I am not very sure how else to solve this particular issue :) get last id form database in laravel-8
You can get the last id using Query Builder
and Eloquent
.
Query Builder
function indextwo() {
return DB::table('products')->orderBy('id', 'DESC')->first();
}
Eloquentfunction indextwo() {
return Product::orderBy('id', 'DESC')->first();
}
Laravel: get last Insert id from query builder
Try it once :-
$id = DB::getPdo()->lastInsertId();
Related Topics
How to Select Year and Month from the Created_At Attributes of Database Table in Laravel 5.1
Randomize a PHP Array with a Seed
SQL - Insert and Catch the Id Auto-Increment Value
Number in the Top-Level Domain
How to Use a PHP Class from Another File
Laravel Catch Eloquent "Unique" Field Error
Doctrine 2 Lifecyclecallbacks with Abstract Base Class Are Not Called
Why Should I Never Run 'Composer Update' in Production
Using Moodle Create Users and Enroll Them in Courses via SQL
Jquery:: Ajax Powered Progress Bar
Find in Set in Laravel? Example
PHP Prepared Statements and Transactions in a Loop
How to Find "Related Items" in PHP
"Call to Undefined Function" Error When Calling Class Method