Laravel , geeting comma separated values as ID for another model - php

so i have this input from invoice_table, "order_numbers", with values something like this : 91,92,93
in controller :
$invoice->order_numbers = Input::get('order_numbers');
What i need is to find that order numbers ( 91,92,93 ) in orders_table and updated it's value
This is what i try in controller :
$invoice->order_numbers = Input::get('order_numbers');
$orderIds = explode(',', $invoice->order_numbers);
$cnt = count($orderIds);
for ($i = 0; $i < $cnt; $i++) {
$order = Order::findOrFail($orderIds);
$order->is_billed = '1';
$order->save();
}
but i got this error :
BadMethodCallException in Macroable.php line 74:
Method save does not exist.
Can somebody help me what to do ? Thanks

You can change all your code to:
$orderIds = explode(',', request('order_numbers'));
Order::whereIn('id', $ordersIds)->update(['is_billed' => 1]);
Your code will generate N * 2 queries (200 queries for 100 IDs) and this code will generate just one query for any number of IDs.
update() method uses mass assignment, so make sure is_billed is in $fillable array.

Related

how to fix Object of class Illuminate\Support\Collection could not be converted to int?

I want to retrieve the data that stores the total questions on a quiz, but when I loop using the result of the total question data that I got using the query below, the result shows Object of class Illuminate \ Support \ Collection could not be converted to int. does anyone know how to solve it?
Here is the error
Here is my code
public function insertStdAnswer(Request $request,$id){
$_num = DB::table('quiz')
->select('question_total')
->where('id', $id)
->get();
for($i = 0; $i <= $_num ; $i++){
$quiz_id = $id;
$user_id_std_quiz = Auth::id();
$std_answer = $request->input('answer-'.$i);
$nomor_quiz = $request->input('soal-'.$i);
DB::insert('insert into studentquiz (`std_quiz_id`,`user_id_std_quiz`,`std_answer`,`nomor_quiz`) values(?,?,?,?)',
[$quiz_id,$user_id_std_quiz,$std_answer, $nomor_quiz]);
}
I think you should use ->value('question_total')
$_num = DB::table('quiz')
->where('id', $id)
->value('question_total');
use count($_num) instead of $_num in for loop
You are comparing $i with a collection.
As you are using $_num to assign data which you have queried form the database using the get() method, your $_num has become a collection object, as any query in Laravel returns a collection object. To use it in your for() loop as in integer value you will have to count the collection to get an integer value. you can use the following code instead of your current for loop:
for($i = 0; $i <= count($_num) ; $i++){
// your code
}

Adding items into array Laravel using for loop

I am trying to get all categories that have products from the database and push them into another array.
I have four 3 categories and two of them have products.
Here is my code:
$categories = Category::all();
$count = count($categories);
$categoriesWithProducts = array();
for($i = 0; $i < $count; $i++) {
if($categories[$i]->products->count() > 0) {
array_push($categoriesWithProducts, $categories[$i]);
}
return response()->json($categoriesWithProducts);
}
I get an array with just one item instead of two.
Where am i going wrong?
Although error is obvious (mentioned in comment) you could rewrite the whole thing:
$categories = Category::withCount('products')->get(); // you load count to not make n+1 queries
$categoriesWithProducts = $categories->filter(function($category) {
return $category->products_count > 0
})->values();
return response()->json(categoriesWithProducts);
Of course you could make it even simpler:
return response()->json(Category::withCount('products')->get()
->filter(function($category) {
return $category->products_count > 0
})->values()
);
But in fact the best way would be using Eloquent relationships so you could use:
return response()->json(Category::has('products')->get());

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']));
}

Update one-to-many relation in Laravel: Array to string conversion error

I'm trying to update multiple rows but I face an array to string conversion error. Donation to Donation Items is a one-to-many relation and up to 5 types of items may be updated. I've already tried using solution from Update multiple rows of database in Laravel and used the saveMany() method but I'm still not able to update the given rows.
Here's what I tried:
$n = 0;
$donationItems = DonationItems::where('donation_id', $donationId)->get();
foreach ($donationItems as $item) {
$itemName = $r->get('item-name');
$itemQuantity = $r->get('item-quantity');
$item->name = $itemName;
$item->quantity = $itemQuantity;
$item->donation_id = $donation->id;
$donation->donationItems()->save($item);
$n += 1;
}
Change your line
$donation->donationItems()->save($item);
For
$item->save();
Since you already set the donation_id on your $item, you don't need to save them through the relation
You can just use update() method which will create just one query instead of N queries:
DonationItems::where('donation_id', $donationId)
->update([
$item->name = $r->item-name;
$item->quantity = $r->item-quantity;
$item->donation_id = $donation->id;
]);
This will work as long as you're properly using $fillable array in the model:
protected $fillable = ['name', 'quantity', 'donation_id'];

Laravel eloquent where returns result only for first element in foreach?

I'm having a simple hasMany relation between order and orderItems. What I'm trying to do is fetch the count of similar order items. This is what I've done:
$orderItems = $order->orderItems();
$distinctItems = $orderItems->groupBy('item_name')->distinct('item_name')->get();
foreach($distinctItems as $i){
$i['count'] = $orderItems->where('item_name', '=', $i->item_name)->count();
}
$order['items'] = $distinctItems;
However the count is returned for only first order Item and 0 for other items. I'm not sure why this is happening. I've also checked that where() returns null for the items except the first one.
Thanks for the help.
try using the collection only, first groupBy item_name and then on each item add count and return new collection which would look something like
$orderItems = $order->orderItems()->get();
$order['items'] = $orderItems->groupBy('item_name')->map(function($item) {
$i = $item->first();
$i->count = $item->count();
return $i;
});
Try this code.
$cnt = array();
foreach($distinctItems as $i){
$cnt[$i]['count'] = $orderItems->where('item_name', '=', $i->item_name)->count();
}
print_r($cnt);

Categories