updateOrCreate with increment in laravel - laravel

What I am trying to do is to update or insert the row in table. In my case, update looks something like this:
\DB::table('inventories')->where('product_code',$product_code)->increment('stock_current_quantity',$quantity);
I don't want to use if else statement. What I actually want is to integrate increment into following statement so it update as above statement.
\App\Inventory::updateOrCreate(['product_code' => $product_code], ['stock_current_quantity'=>$quantity]);
Thanks in advance!

Because google brought me here and I think the answers here, especially when you simply want to use updateOrCreate, are not as satisfying as this:
\App\Inventory::updateOrCreate([
'product_code' => $product_code
],
[
'stock_current_quantity' => \DB::raw('stock_current_quantity + 1')
]
);
Credits to this guy

Why not do:
$inventory = \App\Inventory::firstOrNew(['product_code' => $product_code]);
$inventory->stock_current_quantity = ($inventory->stock_current_quantity + $quantity);
$inventory->save();
If the model doesn't exists, $inventory->stock_current_quantity will only be equal to $quantity, else, it will increment it by $quantity.

I am using Laravel 7.8.1 and rolling it all into one statement as per the following works fine:
$user->league_entries()->updateOrCreate([
'month' => $month,
'year' => $year
])->increment('score');

just contributing if someone else has this problem
it doesn't exist, creates, but with zero
self::firstOrNew(['product_code' => $product_code]);
then, increment it... if other process updates it to 1 before me (in this middle time between firstOrNew and increment), this will update to 2, avoiding losing the prior update
self::where('product_code', $product_code)->increment('stock_current_quantity');

Similar to Inigo's answer, but slight change i would go with:
$user->league_entries()->firstOrCreate([
'month' => $month,
'year' => $year
])->increment('score');

Related

how to use increment function in laravel

i am using DB to store values in database.
i have "course fees" column i what to "increment" the "course_fees" value in column.
for example
DB::table('student')->where('registration_id','=', $request->registration_id)->increment(['course_fees' =>$request->course_fees]);
this code increment the inserted value
how can i modified below code for increment "course_fees" value like above
DB::table('student')->where('registration_id','=', $request->registration_id)->update(['payment_date' => $request->payment_date,'balance_fees' => $request->balance_fees,'course_fees' =>$request->course_fees]);
You cannot use this method to increment multiple fields. You can use:
$studentQuery = DB::table('student')->where('registration_id','=', $request->registration_id);
(clone $studentQuery)->increment('payment_date',$request->payment_date);
(clone $studentQuery)->increment('balance_fees', $request->balance_fees);
(clone $studentQuery)->increment('course_fees', $request->course_fees);
but this way you will run 3 database queries to update.
But if you are sure there is exactly single record found for registration_id you can do it like this:
$student = DB::table('student')->where('registration_id','=', $request->registration_id)->first();
$student->update([
'payment_date' => $student->payment_date + $request->payment_date,
'balance_fees' => $student->balance_fees + $request->balance_fees,
'course_fees' => $student->course_fees + $request->course_fees
]);
EDIT
If you want to increment only course_fees column and want to update other 2 columns from input you can use:
DB::table('student')->where('registration_id','=', $request->registration_id)
->increment('course_fees' , $request->course_fees, [
'payment_date' => $request->payment_date,
'balance_fees' => $request->balance_fees
])
This is documentation about increment/decrement methods.
increment()/decrement() can take 3 parameters: $column, $amount, $extra.
$column is the field that you want to increment
$amount is by how much you want to increment the field by
$extra is an array of attributes that you also want to update in the query.
If you don't pass an amount the default for $amount is 1.
To achieve what you're after you could do:
DB::table('student')
->where('registration_id', $request->registration_id)
->increment('course_fees', $request->course_fees, [
'payment_date' => $request->payment_date,
'balance_fees' => $request->balance_fees,
]);

What is the correct way to use DB insert with where condition in Laravel

I'm trying to insert data into MYSQL and update if there is already a value there. Can't seem to get the insert statement right. This is what I wrote
DB::insert('insert INTO dataentries (MAth) values(?)',[$total])->where('ID_number', $id_numbers);
You can use an updateOrCreate statement.
Something like this (not tested):
$updateOrCreate = App\Dataentries::updateOrCreate(
['total' => $value],
['id' => $id]
);
https://laravel.com/docs/5.3/eloquent
Use updateOrCreate():
$dataentry = App\Dataentry::updateOrCreate(
['ID_number' => $id_number],
['MAth' => $total]
);

How to access the nth item in a Laravel collection?

I guess I am breaking all the rules by deliberately making a duplicate question...
The other question has an accepted answer. It obviously solved the askers problem, but it did not answer the title question.
Let's start from the beginning - the first() method is implemented approximately like this:
foreach ($collection as $item)
return $item;
It is obviously more robust than taking $collection[0] or using other suggested methods.
There might be no item with index 0 or index 15 even if there are 20 items in the collection. To illustrate the problem, let's take this collection out of the docs:
$collection = collect([
['product_id' => 'prod-100', 'name' => 'desk'],
['product_id' => 'prod-200', 'name' => 'chair'],
]);
$keyed = $collection->keyBy('product_id');
Now, do we have any reliable (and preferably concise) way to access nth item of $keyed?
My own suggestion would be to do:
$nth = $keyed->take($n)->last();
But this will give the wrong item ($keyed->last()) whenever $n > $keyed->count(). How can we get the nth item if it exists and null if it doesn't just like first() behaves?
Edit
To clarify, let's consider this collection:
$col = collect([
2 => 'a',
5 => 'b',
6 => 'c',
7 => 'd']);
First item is $col->first(). How to get the second?
$col->nth(3) should return 'c' (or 'c' if 0-based, but that would be inconsistent with first()). $col[3] wouldn't work, it would just return an error.
$col->nth(7) should return null because there is no seventh item, there are only four of them. $col[7] wouldn't work, it would just return 'd'.
You could rephrase the question as "How to get nth item in the foreach order?" if it's more clear for some.
I guess faster and more memory-efficient way is to use slice() method:
$collection->slice($n, 1);
You can try it using values() function as:
$collection->values()->get($n);
Based on Alexey's answer, you can create a macro in AppServiceProvider (add it inside register method):
use Illuminate\Support\Collection;
Collection::macro('getNth', function ($n) {
return $this->slice($n, 1)->first();
});
and then, you can use this throughout your application:
$collection = ['apple', 'orange'];
$collection->getNth(0) // returns 'apple'
$collection->getNth(1) // returns 'orange'
$collection->getNth(2) // returns null
$collection->getNth(3) // returns null
you may use offsetGet since Collection class implements ArrayAccess
$lines->offsetGet($nth);
Maybe not the best option, but, you can get item from array inside collection
$collection->all()[0]

how to update Cart Options in Codeigniter?

Through Documents provided by Codeigniter Its Cart Library doesnt Update its options We can add the Options like that
$data = array(
array(
'id' => 'sku_123ABC',
'qty' => 1,
'price' => 39.95,
'name' => 'T-Shirt',
'options' => array('Size' => 'L', 'Color' => 'Red')
)
);
$this->cart->insert($data);
Is there any other way or any tutorial to learn how we can update options of Cart just like
$qid = $this->input->post("qid");
$pairs = $this->input->post("pairs");
$males = $this->input->post("males");
$females = $this->input->post("females");
$data = array(
array(
'rowid' => $qid,
'qty' => 1,
'options' => array('pairs' => $pairs, 'males' => $males, 'females' => $females))
);
$this->cart->update($data);
I have searched it but seems no one has made any fix for it?
Though I have not found any solution therefore I am using simple solution and that is just rest the item in cart and adding new item with same id and updated option values. Its not great trick though but it is just working for me.
I am fallen yesterday like this kind of problem then i create Extending / Override update function. Here how to Extending Native library Link : Create CI Library
Here is my modified code in Github Link
I hope it will help someone and also can modify as their need.
No it did not work for me.. but there is no any errors, I check the array within the _update function as well,
Array
(
[id] => 177
[rowid] => 66bd8895e10f189f62bf3a65ada83630
[qty] => 1
[options] => Array
(
[vat] => 0
[discount] => 0
)
)
I know i'ts just too late but I want to share my solution:
I just got the the options in an array and updated it as I wanted and then update the entire options field in the cart with the array content.
Hope this help somebody.
Sorry for the english.
The way I tried was a bit difficult but it works. You can’t just update a single option value. To update you have to pass all the existing values to all the option values with the value you want to update as well.
If you want to update your Size option
$data = array(
‘rowid’ => $yourRowIdHere,
‘options’ => array ( ‘color’ => $yourExistingValue, ‘length’ => $yourExistingValue, ‘size’ => $newUpdatedValue)
));
$this->cart->update($data);
Give it a try :)

How can i use Like in cake php

i want the alternative cakephp code for the above query
Select * from book where title like '%java%;
OK, assuming you are using a find() query.
You can specify the conditions array as follows:
"conditions" => array("Book.title like" => "%java%")
or
"conditions" => array("Book.title like '%java%'")
I think both will work
Docu complex find conditions
$this->Post->find('first', array (
"Author.name" => "Bob",
"OR" => array (
"Post.title LIKE" => "%magic%",
"Post.created >" => date('Y-m-d', strtotime("-2 weeks"))
)
));

Resources