laravel 8 : insert method get last insert id in eloquent (İnsert Method) - laravel

I am performing a database operation with "Eloquent ORM in Laravel". I just want to take the last insert id (not the maximum id) in the database.
I searched to get last insert id in laravel Eloquent ORM, I got following link (Laravel, get last insert id using Eloquent) that is refer to get last insert id from following function "$data->save()".
But I need to get
"Model::insert($data)";
My Query:
$insert = Product::insert($alldata);
if ($insert) {
return response()->json([
'success' => 'Ürün başarıyla Eklendi.',
'id' => ???????
]);
}
How can I retrieve the last inserted id?

$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.

You can Also Use insertGetId() function
$id = DB::table('table_name')-> insertGetId($alldata);

Related

get latest record against foreign key and check whether its specific column has value NULL or not

Hi I am working on a project Laravel where I need to update record in database by fetching last(latest) record against foreign key, The scenario is fetch latest record(row) and if its specific column (amendments_to) has NULL value update it with some string else insert a new record. Below is my code what it does is always updates last row only no matter what the value in amendments_to column is.
OrderResponse::where('send_id', $id)
->orderBy('id', 'desc')
->take(1)
->update(['amendments_to' => $request->comment]);
If you only are doing it with a single row at a time, i would simply do a more Eloquent approach. Laravel has a helper for latest() query.
$orderResponse = OrderResponse::where('send_id', $id)
->latest()
->first();
if (!$orderResponse->amendments_to) {
$orderResponse->amendments_to = $request->comment;
$orderResponse->save();
} else {
$newOrderResponse = new OrderResponse([
'amendments_to' => $request->comment,
'send_id' => $id,
// other fields
]);
$newOrderResponse->save();
}

Laravel 8.0 facing issue while trying to update a table with vue form, 'Attempt to read property \"item_id\" on null'

So, i have a table called Items table and another table called item_quantities, on item_quantities ive a column named item_id which is connected to items table id. All the fillable properties on both tables are all in one form on the frontend, and i take care of the form fields on the backend
Whenever i try to update the quantity on the form which is from item_quantities's table with a form, i'm facing serious issue updating the item_quantities. getting Attempt to read property "item_id" on null.
It all started when i noticed a duplicate entries on the item-quantities table, so i deleted all the datas on it..
Here's is the form screenshot
The vue form
and the backend logic
public function saveData(Request $request, $id) {
// dd($request->name);
$updateGroceries = Item::where('id', $request->id)->get()->first();
$updateGroceries->update([
'name' => $request->name,
'description' => $request->description,
'price' => $request->price,
]);
if($updateGroceries) {
$item_quantity = ItemQuantity::where('item_id', $updateGroceries->id) ?
ItemQuantity::where('item_id', $updateGroceries->id)->get()->first() :
new ItemQuantity;
if($item_quantity->item_id == null) {
$item_quantity->item_id = $updateGroceries->id;
}
$item_quantity->quantity = $request->quantity;
$item_quantity->save();
}
}
I'M SO SORRY IF MY ENGLISH WAS'NT CLEARED ENOUGH
Thanks in anticipation
You can simply use firstOrNew() method. This will first find the item, if not exist create e new instance.
$item_quantity = ItemQuantity::firstOrNew(['item_id' => $updateGroceries->id]);
$item_quantity->quantity = $request->quantity;
$item_quantity->save();
Note that the model returned by firstOrNew() has not yet been persisted to the database. You will need to manually call the save method to persist it.
Actually your errors workflow as that:
$item_quantity=null;
$item_quantity->item_id;
You can do that with optional global helper:
optional($item_quantity)->item_id ?: 'default value';

How to get currently inserted row id in laravel 5.5

Here I am using laravel 5.5. My code is
$result = DB::insert('INSERT INTO .......');
Here it returns true. But how can I get inserted id? In my table id is the primary key. Thanks in advance
you can use insertGetId().
If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:
$id = DB::table('users')->insertGetId(
['email' => 'john#example.com', 'votes' => 0]
);
doc can be found here.
Instead of using DB method you can simply use Laravel eloquent:
$result = <YOUR_MODEL_NAME>::create(<YOUR_DATA>)->id();
it return the last inserted record id.
And make sure if you use this method you need to add $fillable in your MODEL like:
class <YOUR_MODEL> extends Model
{
protected $fillable = [ 'column_name_1', 'column_name_2', .., 'column_name_n' ];
}
Why don't you order your rows and get last id?
select <primary key> from <table> order by desc limit 1;
$result = MODEL_NAME::create(data);
return $result->id;
try this may be it's working

How to get product after insert and update in query builder

I'm trying to get the same result as in Eloquent when create and update will return the model back.
In the case of query builder, how can I return the model when insert returns boolean and update returns the ID of the updated row?!?!?
For example: DB::table('users')->insert( ['email' => 'john#example.com', 'votes' => 0] );
Will return boolean, instead what I am looking for is to get that created user, same behavior with User::create().
DB::table('users')->update() will return the ID of the updated row, again I want the updated row as an object same behavior with User::update().
I know that insertGetId() will give me the ID when I use insert(), but I don't want to make an extra step to use the ID and find the row.
Also, for the update, I don't want to use the ID that update() returns to use it in order to find the row.
Does that make any sense?
Use insertGetId() instead of insert() and then find() the model. For example:
$id = DB::table('users')->insertGetId(['name' => 'Ivanka', 'email' => 'ivanka#ivanka.com']);
$user = User::find($id);
When you are updating you have the id, so just find() it: User::find($id).
Documentation that explains how insertGetId() works: https://laravel.com/docs/5.7/queries#inserts
also, you can use from below code if you want.
find the last insert column:
$last_id = Illuminate\Support\Facades\DB::getPdo()->lastInsertId();
and next:
$user = User::find($last_id);

Laravel 5.5 - update or create bulk insert

i am trying to preform update or create action on many records using laravel model.
Normal insert with updateOrCreate works perfectly with foreach but i want to avoide it as it slowing things down.
I have something like 200k records.
Is there is any way to achive it?
I tried this answer below
https://stackoverflow.com/a/34815725/1239122
But it is not super elegant.
Any ideas?
You can try this library for batch insert and update.
https://github.com/mavinoo/laravelBatch
I didn't find a way to bulk insert or update in one query. But I have managed with only 3 queries. I have one table name shipping_costs. Here I want to update the shipping cost against the shipping area. I have only 5 columns in this table id, area_id, cost, created_at, updated_at.
// first get ids from table
$exist_ids = DB::table('shipping_costs')->pluck('area_id')->toArray();
// get requested ids
$requested_ids = $request->get('area_ids');
// get updatable ids
$updatable_ids = array_values(array_intersect($exist_ids, $requested_ids));
// get insertable ids
$insertable_ids = array_values(array_diff($requested_ids, $exist_ids));
// prepare data for insert
$data = collect();
foreach ($insertable_ids as $id) {
$data->push([
'area_id' => $id,
'cost' => $request->get('cost'),
'created_at' => now(),
'updated_at' => now()
]);
}
DB::table('shipping_costs')->insert($data->toArray());
// prepare for update
DB::table('shipping_costs')
->whereIn('area_id', $updatable_ids)
->update([
'cost' => $request->get('cost'),
'updated_at' => now()
]);
You can use insert() in Query Builder to bulk insert. But update statement needs conditions. Please read the document:
https://laravel.com/docs/5.7/eloquent#updates
As far as I know, you can not do it for the update as you need to check the condition for the update, But you can do it for insert
$data = array(
array('name'=>'John', 'phone'=>'1234567890'),
array('name'=>'Deo', 'phone'=>'9876543210'),
//...
);
Model::insert($data);

Resources