Automatically use Timestamp in Laravel 5.4 Query builder - laravel

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();

Related

Laravel firstOrNew based on created_at same date

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

updateOrCreate isn't filling all the fields in Laravel 5.6

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

Laravel Update Multiple Columns with QueryBuilder

I'm using Query builder, I successfully update na first column but on the second query the change doesnt happen, I already checked the view part the name of input and its correct. here is my code.
DB::table('area')
->where('id', $request->get('area_id'))
->update(['island_group_id' => $request->get('island_group_id')],
['region_id' => $request->get('region_id')]);
return 'test';
$updateDetails = [
'island_group_id' => $request->get('island_group_id'),
'region_id' => $request->get('region_id')
];
DB::table('area')
->where('id', $request->get('area_id'))
->update($updateDetails);
DB::table('area')
->where('id', $request->get('area_id'))
->update([
'island_group_id' => $request->get('island_group_id'),
'region_id' => $request->get('region_id')
]);
return 'test';
I think it will be helpful to you.
$area_id = $request->get('area_id');
$island_group_id = $request->get('island_group_id');
$region_id = $request->get('region_id');
$update_details = array(
'island_group_id' => $island_group_id
'region_id' => $region_id
);
DB::table('area')
->where('id', $area_id)
->update($update_details);
Because you use every time new array for update field. Please use one array for update multiple field like:
DB::table('area')
->where('id', $request->get('area_id'))
->update(array(
'island_group_id'=>$request->get('island_group_id'),
'region_id'=>$request->get('region_id')
));

Will Model::updateOrCreate() update a soft-deleted model if the criteria matches?

Let's say I have a model that was soft-deleted and have the following scenario:
// EXISTING soft-deleted Model's properties
$model = [
'id' => 50,
'app_id' => 132435,
'name' => 'Joe Original',
'deleted_at' => '2015-01-01 00:00:00'
];
// Some new properties
$properties = [
'app_id' => 132435,
'name' => 'Joe Updated',
];
Model::updateOrCreate(
['app_id' => $properties['app_id']],
$properties
);
Is Joe Original now Joe Updated?
OR is there a deleted record and a new Joe Updated record?
$variable = YourModel::withTrashed()->updateOrCreate(
['whereAttributes' => $attributes1, 'anotherWhereAttributes' => $attributes2],
[
'createAttributes' => $attributes1,
'createAttributes' => $attributes2,
'createAttributes' => $attributes3,
'deleted_at' => null,
]
);
create a new OR update an exsiting that was soft deleted AND reset the softDelete to NULL
updateOrCreate will look for model with deleted_at equal to NULL so it won't find a soft-deleted model. However, because it won't find it will try to create a new one resulting in duplicates, which is probably not what you need.
BTW, you have an error in your code. Model::updateOrCreate takes array as first argument.
RoleUser::onlyTrashed()->updateOrCreate(
[
'role_id' => $roleId,
'user_id' => $user->id
],
[
'deleted_at' => NULL,
'updated_at' => new \DateTime()
])->restore();
Like this you create a new OR update an exsiting that was soft deleted AND reset the softDelete to NULL
Model::withTrashed()->updateOrCreate([
'foo' => $foo,
'bar' => $bar
], [
'baz' => $baz,
'deleted_at' => NULL
]);
Works as expected (Laravel 5.7) - updates an existing record and "undeletes" it.
I tested the solution by #mathieu-dierckxwith Laravel 5.3 and MySql
If the model to update has no changes (i.e. you are trying to update with the same old values) the updateOrCreate method returns null and the restore() gives a Illegal offset type in isset or empty
I got it working by adding withTrashed so that it will include soft-deleted items when it tries to update or create. Make sure deleted_at is in the fillable array of your model.
$model = UserRole::withTrashed()->updateOrCreate([
'creator_id' => $creator->id,
'user_id' => $user->id,
'role_id' => $role->id,
],[
'deleted_at' => NULL
])->fresh();
try this logic..
foreach ($harga as $key => $value) {
$flight = salesprice::updateOrCreate(
['customerID' => $value['customerID'],'productID' => $value['productID'], 'productCode' => $value['productCode']],
['price' => $value['price']]
);
}
it work for me

Eloquent update and limit

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));

Resources