How to get last inserted id through save() method in laravel - php

I know to get the last id I can use insertGetId() but I want to know how can I get the last inserted id through save() method.
order = new Store_order;
$order->invoice_id = $signed['invoice_id'];
$invoice = $order->save()['so_id'];
I used this but it returns null value

After $order->save(), $order->so_id should be the last id inserted. Your code should be as below.
$order = new Store_order;
$order->invoice_id = $signed['invoice_id'];
$order->save();
$invoice = $order->so_id;

You can get it by like below :
$order = new Store_order;
$order->invoice_id = $signed['invoice_id'];
$invoice = $order->save();
echo $invoice->so_id;
in this case you no need to store in one variable and then access it, You can get the inserted records by calling the model object itself :
$order = new Store_order;
$order->invoice_id = $signed['invoice_id'];
$order->save();
// echo $order; => will return entire stored last record.
echo $order->so_id;
Make sure so_id is autoincrement.

Try this once it worked for me where $mode->save(); was only returning true.
$mylastid = DB::getPdo()->lastInsertId();

In case of you did overwride the name of primary key in the model as in next case:
protected $primaryKey = 'your_table_id_name';
use:
$id = $your_variable_save->your_table_id_name
if not:
$id = $your_variable_save->id

You can get the last inserted id by the following codes.
Using Laravel Eloquent
$order = new Store_order();
$order->invoice_id = $signed['invoice_id'];
$order->save();
$lastInsertedId = $order->so_id; //now getting Last inserted id
echo $lastInsertedId;
Provided that $order->so_id means last inserted id of the given object where so_id is the primary key of the table.

$ObjTable->nane = $name;
$ObjTable->save();
echo $ObjTable->id;
this will be display last inserted id.

Related

How to use update() functionality in Laravel?

Inside my store function i have to search a name of a particular person, thus:
$person = DB::select("select p.* from persons p where concat_ws(', ' ,p.family_name,concat_ws(' ',concat_ws(' ',p.first_name,p.middle_name),p.third_name)) like ?", [$request['person_name']]);
If this person exist i have to update the person and this one works:
Person::where('id', $person[0]->id)->update(['status' => 'Active']);
but not this one:
$person[0]->status = 'Active';
$pArray = json_decode(json_encode($person[0]), true);
$per = new Person($pArray);
$per->update();
Since you have already created a new model instance, you would need to call the save() method.
$per = new Person($pArray);
$per->save();
Or, you can use update() to pass data into an existing model. But first, you need to retrieve the model you want to update.
$per = Person::find($pArray['id']);
$per->update($pArray);
Use your search query instead of mine. I think this will help you.
$result = User::where('id', $userId)->first();
$result->name = 'xyz';
$result->update();
For update data in laravel using model you need to pass where condition in it.
Sample example
$flight = App\Flight::find(1);
$flight->name = 'New Flight Name';
$flight->save();
Hope this helps you!

Duplicating data in Controller Laravel

I am trying to duplicate data with a click of a button, in better terms, trying to reorder a previous order. This is my code
$order = Order::find($id);
$order_details = OrderDetail::where('order_id', $id)->get();
$reorder = $order->replicate();
$reorder_details = $order_details->replicate();
$reorder->save();
$reorder_details->save();
The $order data replicates fine, however the $order_details data doesnt, as I get this error Method Illuminate\Database\Eloquent\Collection::replicate does not exist.
Is there a way to duplicate without using replicate()?
It's because $order = Order::find($id); returns the first instance (a model) and $order_details = OrderDetail::where('order_id', $id)->get(); returns a collection. Just have to change it to $order_details = OrderDetail::where('order_id', $id)->first(); and it will work fine.
To handle multiple order details:
$order_details = OrderDetail::where('order_id', $id)->get()->each(function($item) use($reorder){
$newItem = $item->replicate();
$newItem->order_id = $reorder->id; //If needed, be sure to pass $order if you do
$newItem->save();
});
You can use the __clone() method which you can implement inside the order class,
Then you can use it like this
$order = Order::find($id);
$newOrder = clone $order;
$newOrder->save();

Laravel, copy row to another table with eloquent relationship

I want to get the data form database table and create a new row in another table.
Which 1 PO have many PoProducts.
$_getPO = Order::find($id);
$_getPOProducts= OrderProducts::where('order_id', $id)->get();
$order_no = $_getPO->order_no;
$eta = $_getPO->eta;
$_Order = new DeliveryOrders();
$_Order->order_no = $order_no;
$_Order->eta = $eta;
$_Order->save();
$POProduct = array();
foreach($_getPOProducts as $i => $_getPOProduct)
{
$POProduct[] = new DeliveryOrderProducts();
$POProduct[] = $_getPOProduct->order_id;
$POProduct[] = $_getPOProduct->item_id;
$POProduct[] = $_getPOProduct->qty;
$POProduct->save();
}
But, this output an error.
Call to a member function save() on array
Please help me. Thanks.
If you wish to copy records from one table to another or just duplicate a record in the same table you could simply use the repliacate() method.
$user = User::findOrFail($id);
// replicate (duplicate) the data
$staff = $user->replicate();
// make into array for mass assign.
//make sure you activate $guarded in your Staff model
$staff = $staff->toArray();
Staff::firstOrCreate($staff);
Note: in case you're only duplicating on the same table replace Staff with User on this example.
You are trying to run the save method on the array but what you want is to use it on the array index instead.
Change your foreach to this and it should work (assuming columns are the same).
foreach($_getPOProducts as $i => $_getPOProduct)
{
$POProduct[$i] = new DeliveryOrderProducts();
$POProduct[$i]->order_id = $_getPOProduct->order_id;
$POProduct[$i]->item_id = $_getPOProduct->item_id;
$POProduct[$i]->qty = $_getPOProduct->qty;
$POProduct[$i]->save();
}
You can shorten this by using forceCreate.
foreach($_getPOProducts as $i => $_getPOProduct)
{
$POProduct[$i] = (new DeliveryOrderProducts())->forceCreate($_getPOProduct->only(['order_id', 'item_id', 'qty']));
}

Laravel update multiple database rows with Eloquent

I want to update the products leased count when a product is rented to a customer.
The owner of the website can rent multiple things. I do this by cloning with Ajax.
Now, when someone has rented like 2 chairs and 1 table, i want to update the products_leased row for both products. How would i do that?
The error i get:
`SQLSTATE[01000]: Warning: 1265 Data truncated for column 'product_leased' at row 1 (SQL: update `products` set `product_leased` = 3 5, `updated_at` = 2017-06-07 19:57:03 where `id` = 1)`
My controller:
public function create_order($id) {
$customer = Customer::find($id);
$pr = Product::get();
$rent_from = Request::input('rent_from');
$rent_till = Request::input('rent_till');
$productArray = Request::get('product_name');
$productCountArray = Request::get('product_count');
$rentProduct = new cRent;
$rentProduct->customer_id = $customer->id;
$rentProduct->rent_from = $rent_from;
$rentProduct->rent_till = $rent_till;
$rentProduct->rented_products = implode(', ', $productArray);
$rentProduct->rented_products_count = implode(', ', $productCountArray);
$rentProduct->save();
$pru = Product::find($id);
$pru->product_leased = implode(' ', $productCountArray);
$pru->update();
return back();
}
The code above works only when one product has been rented. Not when i rent 2 products.
Thanks in advance.
Why are you passing in the same $id to
$customer = Customer::find($id);
and
$pru = Product::find($id);
?
Instead of imploding the product names and counts and storing them together, why not create separate rent records for each product and relate them as a one-to-many? Assuming product name and product count line in the arrays, something to the effect of:
foreach(array_combine($productArray, $productCountArray) as $product_name => $count){
$product = Product::where('name', $product_name)->first();
$rentProduct = new cRent;
$rentProduct->customer_id = $customer->id;
$rentProduct->rent_from = $rent_from;
$rentProduct->rent_till = $rent_till;
$rentProduct->product_id = $product->id
$rentProduct->count = $count;
$rentProduct->save();
}
Better yet, don't pass in the product names, instead pass the product ids in from the form.
$rentProduct = new cRent;
the code above indicates only one instance of your cRent off-course if you want have another transaction with the database with a different values or data another instance is needed
I think what you want is something like this
public function create_order($id) {
$customer = Customer::find($id);
$pr = Product::get();
$rent_from = Request::input('rent_from');
$rent_till = Request::input('rent_till');
$productArray = Request::get('product_name');
$productCountArray = Request::get('product_count');
foreache($productArray as $prod){
$rentProduct = new cRent;
$rentProduct->customer_id = $customer->id;
$rentProduct->rent_from = $rent_from;
$rentProduct->rent_till = $rent_till;
$rentProduct->rented_products = $prod
$rentProduct->rented_products_count = //not sure in this line
$rentProduct->save();
}
$pru = Product::find($id);
$pru->product_leased = implode(' ', $productCountArray);
$pru->update();
return back();
}

Laravel how to update value in mysql only if value is changed

I'm new to Laravel. All I'm trying to do is as follow:
I have some fields in my form like TITLE, DESCRIPTION.
TITLE field is unique in database.
This is what I've done to update my values.
$product = Product::find($id);
$product->title = $request->title;
$product->description = $request->description;
$product->save();
But this will give error (that value already exists) as my TITLE field is unique.
All I want to is update my TITLE only if the TITLE value is changed otherwise update the same value but update other fields. Thanks
Something like this?
$product = Product::find($id);
if ($product->title == $request->title) {
$product->description = $request->description;
} else {
$product->title = $request->title;
}
$product->save();
The code you posted does exactly (if indirectly) what you say you want. Your problem is another: you're assigning a title that is used elsewhere, thereby violating uniqueness.
You must verify that the new title is not already used.
$duplicate = Product::where('title', '=', $request->title)->where('id', '!=', $id)->first();
At this point it is unclear what you want to do:
a) Do you want to use the duplicate record instead of the one indicated by $id?
b) Is this an error?
c) Should the $id record be updated, leaving the title alone?
You can do any of these things; what you can't do is "update my TITLE only if the TITLE value is changed", because the changed value is already in use elsewhere.
I have not seen any of your database structure or form code only the small snippet above you have stated.
you could do something like this...
$checkTitle = Product::where('title', '=', $request->input('title')->first();
You can also do...
$record = Product::find($id)
if($request->input('title') === $record->title){
// Record with the $id has the same title as you are posting in the request.
}else{
// Title for $id lets say id number 3, Is not the same as the form request you are sending so now Perform insert
}
if(count($checkTitle) >= 1){
// Means the title exists and do what ever you want...
// Perform update
}else{
// Perform insert
}
Sorry for short and sweet, leaving to go to office and thought it might help to post now. Let me know if im on the wrong tracks and ill help where i can.
You can use if statement to check weather column value is same with original?
$currentProduct = Product::find($id);
//Check and update if title not same
if($currentProduct->title == $request->title){
$currentProduct->description = $request->description;
}
//Update title and description...
else {
$currentProduct->title = $request->title;
$currentProduct->description = $request->description;
}
$currentProduct->save();
You should look at wasChanged() function in Laravel.

Categories