laravel how to revert only last items deleted by soft delete - laravel

i have cart table that save all customer orders in there.
+------------------------------------------------------------------------------+
| id | user_id | product | created_at | updated_at | deleted_at |
+------------------------------------------------------------------------------+
when user soft delete we want to soft delete all items in his cards
when user want to revert we want to revert those items that soft deleted in last time
i can implement it.
this is revert function in my code:
public function revertBackDeletedItems(Request $request)
{
$user = apiGetUser();
if ($user == null) {
return apiAbort(401);
}
$purchaseCartCount = $user->cart()->onlyTrashed()->count();
if ($purchaseCartCount == 0) {
return [
'success' => false,
'message' => 'no items in card '
];
}
$purchaseCartDateTimeInLatestDelete = $user->cart()->onlyTrashed()->orderBy('id', 'desc')->first()['deleted_at'];
$purchaseCarts = PurchaseCart::onlyTrashed()->where('user_id', $user->id)->where('deleted_at', $purchaseCartDateTimeInLatestDelete)->get();
foreach ($purchaseCarts as $key => $purchaseCart) {
$purchaseCart->restore($purchaseCart->id);
}
return ['success' => true];
}
this is the function that delete only the last time items that was deleted?
public function deleteLastTrashed(Request $request)
{
$user = apiGetUser();
if ($user == null) {
return apiAbort(401);
}
$purchaseCartCount = $user->cart()->onlyTrashed()->count();
if ($purchaseCartCount == 0) {
return [
'success' => false,
'message' => 'no items in card '
];
}
$purchaseCartDateTimeInLatestDelete = $user->cart()->onlyTrashed()->orderBy('id', 'desc')->first()['deleted_at'];
$purchaseCarts = PurchaseCart::onlyTrashed()->where('user_id', $user->id)->where('deleted_at', $purchaseCartDateTimeInLatestDelete)->get();
foreach ($purchaseCarts as $key => $purchaseCart) {
$purchaseCart->forceDelete($purchaseCart->id);
}
return ['success' => true];
}
how can i get deleted_at in better way?
this is not a clean code?
i need better way to implement this algorithms

You almost got there:
public function deleteLastTrashed(Request $request)
{
$user = apiGetUser();
if ($user == null) {
return apiAbort(401);
}
$purchaseCartCount = $user->cart()->onlyTrashed()->count();
if ($purchaseCartCount == 0) {
return [
'success' => false,
'message' => 'no items in card '
];
}
// here you know that user has at least one soft deleted cart
$userLastCartSoftDeleted = $user->cart()->onlyTrashed()->orderBy('deleted_at', 'desc')->first();
$userLastCartSoftDeleted->forceDelete();
return ['success' => true];
}

Your could try this:
Add new fields in carts table is_deleted and is_recent so whenever user will delete set is_deleted = 1; and is_recent = 1 to that item which you are going to delete and rest of other is_recent = 0;
During revert fetch that items which have is_recent = 1; and save is_deleted = 1

Related

Single column not being updated in laravel 5

I am tying to update a single column of a table messages and I have the following code:
public function messageSeen(Request $request){
$data = Message::find($request->id);
$success = Message::where('id', $request->id)->update(array('is_seen' => 1));
if($success){
return response()->json(['status'=>'success'], 200);
} else {
return response()->json(['status'=>'Data not updated'], 404);
}
}
I am getting the response Data not updated. If you question, does the column is_seen exists? then yes it does. Even I tried fetching the data having id $request->id, it gives the proper data. I wonder why is the data not being updated? Am I doing right thing to update column or is there an way out to update column in different way?
I tried the other way like the following:
public function messageSeen(Request $request){
$id = $request->id;
$result = Message::find($id);
dd($result->message);
$data = array();
$data['is_seen'] = 1;
$data['message'] = $result->message;
$data['user_id'] = $result->user_id;
$data['conversation_id'] = $result->conversation_id;
$this->messages->fill($data);
$success = $this->messages->save();
if($success){
return response()->json(['status'=>'success'], 200);
} else {
return response()->json(['status'=>'Data not updated'], 404);
}
}
But here I am getting unexpected thing with this method. Here I am being able to do dd($result) and being able to get data like this:
#attributes: array:9 [
"id" => 22
"message" => "How are you?\r\n"
"is_seen" => 0
"deleted_from_sender" => 0
"deleted_from_receiver" => 0
"user_id" => 2
"conversation_id" => 1
"created_at" => "2019-09-29 03:42:39"
"updated_at" => "2019-09-29 03:42:39"
]
however, if I tried to do dd($result->message) then I get null! What am I doing wrong?
I tried the following code:
public function messageSeen(Request $request){
$id = $request->id;
$result = Message::find($id);
$data = array();
$data['is_seen'] = 1;
$data['message'] = $result[0]['message'];
$data['user_id'] = $result[0]['user_id'];
$data['conversation_id'] = $result[0]['conversation_id'];
$this->messages->fill($data);
$success = $this->messages->save();
if($success){
return response()->json(['status'=>'success'], 200);
} else {
return response()->json(['status'=>'Data not updated'], 404);
}
}
and it worked but instead of updating it is adding new column when the message is seen. But first I don't understand why do I have to do $result[0]['key'] in the first place.
You need to specify which fields in your table can be mass assigned, by adding or updating the $fillable property of your model:
protected $fillable = [..., 'is_seen', 'message', ...];
This is required for the create() and update() methods, as those accept "mass" variables in the array you pass in. Whereas with save() you have to manually, explicitly, assign the properties on the model, so there is no risk of accidentally saving something you didn't mean to. And this is exactly the behaviour you are seeing - update() is not working, but save() is.
You should try this
public function messageSeen(Request $request) {
$input = Request::all();
$data = Message::find($input['id']);
if (!empty($data)) {
$update = array();
$update['is_seen'] = 1;
$success = Message::where('id', $input['id'])->update($update);
if ($success) {
return response()->json(['status' => 'success'], 200);
} else {
return response()->json(['status' => 'Something went wrong'], 400);
}
} else {
return response()->json(['status' => 'Data not updated'], 404);
}
}
Value depends on data type of is_seen are string or integer

update multiple rows after insert in codeigniter

After insert I want to update field with ($id.'mytext') where in db that field is empty for all rows.
table name: peca
columns:
id -autoincrement
A -varchar user insert
CB -varchar auto insert with update
MODEL WILL RETURN ALL ROWS WHERE CB=empty
function model1() {
$this->db->select('*');
$this->db->from('peca');
$this->db->where('CB', '');
//$this->db->where('id', $fileid);
$query = $this->db->get();
if ($query) {
return $query->result();
} else {
return false;
}
}
MODEL WILL update in db where CB=empty
function model2($dados = NULL) {
if ($dados !== NULL) {
// extract($dados);
$this->db->where('CB', '');
$this->db->update('peca', $dados);
return true;
} else {
return false;
}
}
CONTROLLER
$this->load->model('model_peca');
$resultadocadastropeca = $this->model_peca->model1($id);
$data = 'id' => $id;
$appointment = array('codigoean' => $data.'.PECA.');
$appointment = $this->model_peca->model2($appointment);
START TABLE
Previous values inserted from import so CB can only be generated after id exists
id|CB |
22| |
31| |
RESULTS
I'm changing CB to .PECA. in all rows where CB=empty but $id for each row is not passing
id|CB |
22|.PECA.|
31|.PECA.|
EXPECTED
id|CB |
22|22.PECA.|
31|31.PECA.|
I still don't fully understand what you want to do, but if you want to fetch something where a column is empty or null:
$this->db->where("WHERE yourColumn IS NULL OR yourColumn = ''");
As per your revised question, this should work:
$this->db->select('id');
$this->db->where('CB', '');
$q = $this->db->get('peca');
if ($q->num_rows() == 0) {
die('nothing to do here');
}
$res = $q->result();
foreach ($res as $item) {
$data[] = array('id' => $item->id, 'CB' => $item->id . '.PECA.');
}
$this->db->update_batch('peca', $data, 'id');

How to get the value of a variable from the collection

public function returnsTrueIfEmailIsVerified(Request $request)
{
// Gets the email
$email = request("email"); //johndoe#example.com for example
// Determine if zero or one ;
$user = User::where('email','=',$email)->get(); // 0 or 1 ;
$userCount = User::where('email','=',$email)->count(); // 0 or 1 ;
$confirmedValue = $user->get('confirmed');
$response ;
if ( $user === 1 && $confirmedValue === true ) {
$response = 'OK';
}
elseif ($user === 1 && $confirmedValue === false) {
$response = 'Not Confirmed yet';
}
else {
$response = 'Not Registered yet';
}
return response()->json(200,$response);
}
with that code I would return a response that if a user isn't registered or is registered and that if he's registered but that he's not confirmed yet..
I want to return something out from that I'm not just familiar with laravel's way
There are so many error in your code, I've fixed it and this code will work. I think you need to learn more Laravel and PHP.
public function returnsTrueIfEmailIsVerified(Request $request)
{
$email = request("email");
$user = User::where('email', '=', $email);
$response = [
'message' => ''
];
if ($user->count() === 1) {
$confirmedValue = $user->first()->confirmed;
if ($confirmedValue) {
$response['message'] = 'OK';
} else {
$response['message'] = 'Not Confirmed yet';
}
} else {
$response['message'] = 'Not Registered yet';
}
return response()->json($response, 200);
}
you can't response string as a json, json is key value pair.
User::where('email', '=', $email) return Query Builder not 0 or 1, use count() method;
you can't retrieve value from multiple items you have to specific item like this $user->get()[0]['confirmed] or use Laravel special method $user->first()->confirmed

updateExistingPivot() not working

I'm trying to update a pivot table like this:
public function updatePermission($id, $permissionId)
{
$permissionValue = Input::get('value');
$user = User::find($id);
$perms = ['value' => $permissionValue];
$user->permissions()->updateExistingPivot($permissionId, $perms);
}
This pivot has been previously created with:
public function attachPermission($id)
{
$permissionId = Input::get('id');
$permissionValue = Input::get('value');
$user = User::find($id);
if (!$user->permissions->contains($permissionId)) {
$user->attachPermissionById($permissionId);
$perms = ['value' => $permissionValue];
$user->permissions()->updateExistingPivot($permissionId, $perms);
} else {
return Response::json(array('error' => 'Permission ' . $permissionId . ' is alreay set for user ' . $user->id));
}
return Response::json(array('role' => User::with(['roles.permissions', 'permissions', 'students'])->find($user->id)));
}
When the updatePermission() method is hit, it passes fine, but it doesn't update the pivot table with the new value. What am I doing wrong here?
I won't tell you why it doesn't work, but I suggest you do this:
public function attachPermission($id)
{
$permissionId = Input::get('id');
$value = Input::get('value');
$user = User::find($id);
$sync = $user->permissions()->sync([$permissionId => compact('value')], false);
return (in_array($permissionId, $sync['updated']))
? Response::json(...) // permission updated
: Response::json(...); // permission added
}
It will add or update new permission for you.

Display multi-option customer attribute within customer management admin grid

Okay so with Customer Attributes I have a multi-option selection that I have added to the Manage Customers Grid.
$prodCode = Mage::getSingleton('eav/config')->getAttribute('customer','prod_codes');
$prodCodeOptions = $prodCode->getSource()->getAllOptions(false);
$prodOptions = array();
foreach($prodCodeOptions as $k)
$prodOptions[$k['value']] = $k['label'];
$this->addColumn('prod_codes', array(
'header' => Mage::helper('customer')->__('Product Code'),
'width' => '100',
'index' => 'prod_codes',
'type' => 'options',
'options' => $prodOptions,
'filter_condition_callback'
=> array($this, '_filterProdOptionsCondition'),
));
I do have my attribute added to the collection at the top of my Grid.php:
->addAttributeToSelect('prod_codes')
Here is my _filterProdOptionsCondition method:
protected function _filterProdOptionsCondition($collection, $column) {
if(!$value = $column->getFilter()->getValue()) {
return;
}
$this->getCollection()->addFieldToFilter('prod_codes', array('finset' => $value));
#print($collection->getSelectSql());
}
Now this work fine and dandy if I only have ONE of the options selected, once I apply more than one option to the customers attribute I will get a blank results within the admin grid, however it IS still searchable.
A close look with the print($collection->getSelectSql()); uncommented I see that the attribute ID values are being returned in an comma delimited list.
Now onto my question with that background laid out, is there a method or "Magento" way to display these multi-options within the admin grid I'm just unaware of? Or do I need to simply get the comma values exploded and call for a new collection to build out the display values? Any help appreciated!
Appears I had to extend the Column renderer to anticipate comma values and simply render them, I'm amazed this isn't built in since the functionality exists to create the multioptions attributes but no grid display option for it.
app/code/local/Mage/Adminhtml/Block/Widget/Grid/Column/Renderer/Options.php
public function render(Varien_Object $row)
{
$options = $this->getColumn()->getOptions();
$showMissingOptionValues = (bool)$this->getColumn()->getShowMissingOptionValues();
if (!empty($options) && is_array($options)) {
$value = $row->getData($this->getColumn()->getIndex());
if (is_array($value)) {
$res = array();
foreach ($value as $item) {
if (isset($options[$item])) {
$res[] = $options[$item];
}
elseif ($showMissingOptionValues) {
$res[] = $item;
}
}
return implode(', ', $res);
}
elseif (isset($options[$value])) {
return $options[$value];
} elseif (is_string($value)) { // <--- MY CHANGES HERE
$values = explode(',', $value);
$returnOptions = "";
foreach($values as $k=>$v) {
$returnOptions .= $options[$v]. ", ";
}
return substr($returnOptions, 0, -2);
}
return '';
}
}

Resources