Laravel increment column in updateOrCreate and get the model - laravel

I am trying to increment a column and updateorcreate a record in one query by doing so:
$model = Model::updateOrCreate([
'email' => $email
], ['received_at' => $received_at])->incremet('received_count');
This does the job as I wanted it too. It updates or create a record and increments the received_count column.
But after the query, I wanted to get the updated/created row, but when I log $model, it only logs 0 or 1. I can confirm that this is because of the ->increment().
But to be honest, I don't know any way how to increment the received_count column other than how I currently did it.
How do I achieve so that it updates or create a record, at the same time increments the received_count column, and after all of this, returns the updated/created object?
As much as posssible, I want this all in one query. Getting the model should be a memory.

$model = Model::updateOrCreate(['email' => $email], ['received_at' => $received_at]);
$model->increment('received_count');
$model->refresh(); // this will refresh all information for your model.
or you can simply:
$model = Model::updateOrCreate(['email' => $email], ['received_at' => $received_at]);
tap($model)->increment('id'); // this will return refreshed model.

just fresh model after incremet:
$model = Model::updateOrCreate([
'email' => $email
], ['received_at' => $received_at]);
$model->incremet('received_count');
$model->fresh();

Related

Laravel create command wont insert a value in database

Hello i am new to Laravel so currently im doing a CRUD. I have created this insert function that works well except one value is never inserted. This is the code below:
public function storeClient(Request $request) {
$request->validate([
'name' => 'required',
'email' => 'required|email',
'phone' => 'nullable',
'age'=>'required',
]);
Client::create($request->all());
dd($request->phone);
return redirect('/')->with('msg', 'Client Saved successfully!.');
}
the phone' => 'nullable', value will not insert in the database unless i update the existing values. I tried this command dd($request->phone); and it shows the correct value from the user input. Any idea why the value will be inserted as null on database?
This is the value output when i make the dd command
I tried this other code which works well but im trying to use the default create() function of laravel. This is the other code i did that works well:
public function storeClient()
{
$client = new Client();
$client->name = request('name');
$client->email = request('email');
$client->phone_number = request('phone');
$client->age = request('age');
$client->save();
return redirect('/')->with('msg','Client Saved successfully!');
}
first i did not like nullable here 'phone' => 'nullable',
then u should see what do you register in your Client table phone_number or phone,
$client->phone_number = request('phone');
i think you should rename your input name phone to phone_number and will work
When you are trying to use default create method the fields names must be same as in database.
$client->phone_number = request('phone');
this line works due to the name you entered manually.
to work with default create method change the name of field in database as phone.

How to prevent duplicates in Laravel Eloquent?

I want to transform my database entry creation inside NewsletterController.php:
$email = $request->input('email');
$table = DB::table('newsletters');
$table->insert(array('email' => $email, 'created_at' => now()));
to prevent duplicate entries. I tried doing this:
$table = DB::updateOrCreate('newsletters');
but this method does not seem to exist for DB. How would I do that?
when you may want to update an existing record in the database or create it if no matching record exists. In this scenario, the updateOrInsert method may be used. The updateOrInsert method accepts two arguments: an array of conditions by which to find the record, and an array of column and value pairs indicating the columns to be updated.
The updateOrInsert method will attempt to locate a matching database record using the first argument's column and value pairs. If the record exists, it will be updated with the values in the second argument. If the record can not be found, a new record will be inserted with the merged attributes of both arguments
DB::updateOrInsert(['email'=>$eamil],['created_at'=>Carbon::now()]);
now, if email exists, the 'created_at' will be updated, otherwise a new row will be inserted with values of the merged array arguments
updateOrCreate you use for Eloquent Builder and updateOrInsert you use for Query Builder. Try with updateOrInsert.
$table = DB::updateOrInsert->table('newsletters')->([ 'id' => $request->id ], [
'email' => $email,
]);
Thanks to Moussab Kbeisy's comment I can validate for uniqueness which will return a 422 error if not met instead of inserting into the database:
$this->validate($request, [
'email' => 'required | unique:newsletters'
]);
$email = $request->input('email');
$table = DB::table('newsletters');
$table->insert(['email' => $email, 'created_at' => now()]);

Laravel - updateOrCreate with large number of records

I have potentially 500,000 records to either insert or update into my database.
I'm using the updateOrCreate function in Laravel but it's still taking a very long time.
I'm current using a foreach loop wrapped in a database transaction but is there a better solution?
DB::transaction(function() use ($items, $client) {
foreach($items as $item) {
$data = array(
'external_id' => $item->external_id,
'comment' => $item->comment,
'code_id' => $item->code_id,
'client_id' => $client->id
);
Registration::updateOrCreate(
[
'user_id' => $item->user_id,
'date' => Carbon::parse($item->date)->format('Y-m-d'),
'session' => $item->session
],
$data
);
}
});
Well since you have so many records its inevitable for it to take a long time, my suggestion is to chunk the data you are getting like so
foreach($items->chunk(1000) as $chunk) {
foreach($chunk as $item) {
...
}
}
The above method will go over 1000 (or as many as you want) items at a time, and should theoretically decrease the load time by a bit. But still I really don't think you can make it a lot faster.
I think you should here use ShouldQueue approach of Laravel
and instead of updateOrCreate method use Query builder to update single row using where('id',$id) this will ma

Pass array into a single column in Laravel

i am trying to pass some values into a single column in laravel database table.
The values are like this 20,45,67,89
but i want them to enter into the colume like this
===USER_ID====
20
45
67
89
I have tried like below, but not working..any suggestions ?
foreach ($request->val2 as $value){
$str_explode = explode(",",$value);
DB::table('retirement')->insertGetId([
'user_id' => $str_explode,
'amount' => $request->val1,
'week' => $request->week
]);
}
Hope this will work
foreach ($request->val2 as $value){
$str_explode = explode(",",$value);
$insert = [];
foreach($str_explode as $str){
$insert[] = [
'user_id' => $str,
'amount' => $request->val1,
'week' => $request->week
];
}
DB::table('retirement')->insert($insert);
I'm not sure i understood your question clearly, i'm assuming you want to insert array to a column:
did you try to set the column in migration to Json?
did you set the $casts in the model to json or array?
protected $casts = [ 'user_id' => 'array' ];
then when you do this, you can have an array added to that column like
Posts::create(['user_id'=>[1,2,3,4]]);
normally the user_id field is set to unsignedBigInt(), that type will not accept anything but integers, you gotta check the migration column type first.
explode() is returning an array, not a single value, that's why it will fail. Instead, you should loop through all values like this:
foreach ($request->val2 as $value){
$str_explode = explode(",",$value);
foreach($str_explode as $str){
DB::table('retirement')->insertGetId([
'user_id' => $str,
'amount' => $request->val1,
'week' => $request->week
]);
}
}
As a side advice, as you are not saving the id returned by insertGetID, you can simply use insert. Moreover, it's usually a good practice to use create because this way you will also save timestamps for created and updated.

Laravel updateOrCreate Timestamp Updating Issue

I am using the updateOrCreate method to check whether data has been changed from a response which is entered in the DB. If the record is new then it successfully adds the correct timestamp. However, I have noticed that the updated timestamp updates record for all of the records. I want this to only update if records have been updated.
But looking at the issue I believe all the records are being updated regardless.
if (isset($customers->Data)) {
foreach ($customers as $customerData) {
if ($customer = $customerData->attributes()) {
if ((string) $customer->CustomerType !== 'A') continue;
if ((string) $customer->CustomerEmail === '') continue;
$customerDb = $this::updateOrCreate(
[
'email' => $customer->CustomerEmail,
'code' => $customer->Customer,
'currency' => $customer->Currency,
],
[
'email' => $customer->CustomerEmail,
'code' => $customer->Customer,
'currency' => $customer->Currency,
'name' => $customer->CustomerName,
'phone' => $customer->CustomerPhone,
'terms' => $customer->Terms,
]
);
}
}
}
The email, code, currency fields will always be unique and the rest to create if these are not present. Should the default behavior be that it updates regardless? What I want to achieve is to only detect if a record has been changed if it has then updated that particular field and update the timestamp if it's not there then create it. Thus filtering out what has been updated and only show these records rather than the whole table.
Sorry but new to Laravel any guidance is welcome thank you.

Resources