I am using lumen. I want to use firstOrNew based on created_at. For example in my table there exists data for created_at = 2021-09-23 14:42:13 . For that cases it will update if request date value become that day. Here I tried with
$tableObj = User::firstOrNew([
'created_at' => Carbon::today() // date('Y-m-d')
]);
$tableObj ->mobile= '5457874545';
$tableObj ->save();
Here it always inserted new row. Thanks in advance
Can You Please Format the date
try
$tableObj = User::firstOrNew([
'created_at' => Carbon::today()->format('Y-m-d') // date('Y-m-d')
]);
$tableObj ->mobile= '5457874545';
$tableObj ->save();
or use UpdateOrCreate method of laravel
$tableObj = User::updateOrCreate(
['created_at' => Carbon::today()->format('Y-m-d')],
['mobile'=>'5457874545']
);
Related
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();
I have a code:-
$tokenUpdated = AppToken::updateOrCreate(
array(
'user_id' => $user_id, 'token' => $token),
array('expiry'=>$expiryTime,
'created_date'=>$created_at,
'modified_date'=>$created_at)
);
Though new rows are being inserted, the expiry, created_date fields values aren't getting saved. They records show NULL value which are default values.
What am I doing wrong?
First you need to check if expiry and created_date are returning values, if so then you could use the updateOrCreate function like this:
$tokenUpdated = AppToken::updateOrCreate(
['user_id' => $user_id, 'token' => $token]
['expiry'=>$expiryTime,
'created_date'=>$created_at,
'modified_date'=>$created_at
]
);
check laravel eloquent documentation: https://laravel.com/docs/5.6/eloquent
I want to update few fields in my table. How it is update query write in lumen. I want to update salutation, name, lastname, address fields with dynamicaly equal to id.
$query = "UPDATEpassengersSETname= ? WHERE (id='1') ";
$update = app('db')->update($query, [$passenger->name,]);
I want to pass id value as dynamically.
Use the update() method with where():
DB::table('passengers')->where('id', $id)->update(['name' => $name, 'lasname' => $lastname]);
Use update
DB::table('passengers')->where('id', $id)->update(['name' => $name, 'lasname' => $lastname]);
$update = app('db')->table('passengers')->where('id', $id)->update(['name' => $name, 'lasname' => $lastname]);
is there any way to automatically use time-stamp when using query builder, currently I'm using CARBON.
here is my code:
DB::table('product_in_out')->insert(
['product_id' => $product_id,
'warehouse_id' => $warehouse_id,
'balance_before' => Product::getProductBalanceOf($action_id, $product_id),
'in' => $product_qty,
'out' => '0',
'after_balance' => Product::getProductBalanceOf($action_id, $product_id)+$product_qty,
'action' => 'ProcurementReceipt',
'action_id' => $action_id,
'created_by' => auth()->user()->id,
'updated_by' => auth()->user()->id,
'is_active' => '1',
'created_at' => \Carbon\Carbon::now(), # \Datetime()
'updated_at' => \Carbon\Carbon::now(),# \Datetime() ]
);
Fields created_at and update_at are part of Eloquent.
You need to use Eloquent instead of query builder to insert and update the record in to database for automatic time handling. Eloquent will handle auto update of updated_at column for you,
here is the way,
If you have model name Product,
$product = new Product();
$product->column_name = $column_value;
....
...
$product->save();
Above code will add time stamp automatically at created_at and updated_at column.
Now use Eloquent to update your records like,
$product = Product::find($id);
$product->update_column_name = $update_value;
...
...
$product->update();
This will update your updated_at column value accordingly.
Hope you understand.
Use Laravel Macros:
https://medium.com/fattihkoca/laravel-auto-save-timestamps-with-query-builder-without-using-eloquent-123f7ebfeb92
It is wise to create a macro to avoid typing the same things every time.
insertTs method inserting records into database with created_at data:
DB::table('users')->insertTs([
'email' => 'john#example.com'
]);
$id = DB::table('users')->insertGetIdTs([
'email' => 'john#example.com'
]);
updateTs method updating records into database with updated_at data:
DB::table('users')
->where('id', 1)
->updateTs(['email' => 'john#example.com']);
deleteTs method deleting records into database with deleted_at data (soft delete):
DB::table('users')
->where('id', 1)
->deleteTs();
I could not figure out how can i use both update and limit methods in laravel eloquent orm.
$affectedRows = Promo::where('used','=',0)
->update(array('user_id' => Auth::user()->id))
->limit(1); // Call to a member function limit() on a non-object
//->take(1); // Call to a member function take() on a non-object
I tried both limit and take methods.
I want to do only one result will be update.
But i think, i can not use limit or take methods on update.
Is there any way to update only one row via eloquent?
Add :
Eloquent ORM
$affectedRows = Promo::where('user_id','=',DB::raw('null'))->take(1)
->update(
array(
'user_id' => Auth::user()->id,
'created_ip' =>Request::getClientIp(),
'created_at' => new DateTime,
'updated_at' => new DateTime
)
);
Query Builder
$affectedRows = DB::table('promos')->whereNull('user_id')
->take(1)
->update(array(
'user_id' => Auth::user()->id,
'created_ip' =>Request::getClientIp(),
'created_at' => new DateTime,
'updated_at' => new DateTime
));
These two codes did not add limit param to the query
Output:
update `promos` set `user_id` = '1', `created_ip` = '127.0.0.1', `created_at` = '2013-06-04 14:09:53', `updated_at` = '2013-06-04 14:09:53' where `user_id` = null
Talking about laravel 5 (not sure about L4), depends on db engine.
MySQL supports limit for update so it works, here is the laravel code that do that:
https://github.com/laravel/framework/blob/5.4/src/Illuminate/Database/Query/Grammars/MySqlGrammar.php#L129
so, first ->limit(1) and then ->update([fields]);
DB::table('table')
->where('field', 'value')
->limit(1)
->update(['field', 'new value']);
I used raw query. There is no method limit/take for update and delete queries on both eloquent and query builder. Use
DB::update(DB::raw("UPDATE query"));
like this.
I have not tried it but the Laravel 4 logic makes me think this syntax would work :
$affectedRows = Promo::where('used','=',0)
->limit(1)
->update(array('user_id' => Auth::user()->id));