$ahorroga = Ahorroga::findOrFail($id);
$ahorroga->junta_id = $request->junta_id;
$ahorroga->socio_id = $request->socio_id;
$ahorroga->ahorro = $request->ahorro;
$ahorroga->estado = $request->estado;
if ($ahorroga->isDirty()) {
$ahorroga->save();
toast('Ahorro Garantia Editado', 'success');
return redirect('ahorroga');
}
toast('No se detectaron cambios', 'error');
return redirect('ahorroga');
I know I can use and save lines of code, But how to apply the isDirty
Ahorroga::findOrFail($id)->update($request->all());
If I get it correct, then if you want to detect whether you updated stuff updated the table or not then below is the solution.
The best solution for this is to use update(), it returns true or false and based on this you can do your further logic. For ex:
$ahorroga = Ahorroga::find($id);
$ahorroga->junta_id = $request->junta_id;
$ahorroga->socio_id = $request->socio_id;
$ahorroga->ahorro = $request->ahorro;
$ahorroga->estado = $request->estado;
$id_updated = $ahorroga->update();
if($id_updated ) {
//if ture
}else{
//false
}
public function update($id)
{
$ahorroga->fill($request->only([
'junta_id', 'socio_id', 'ahorro','estado',
]);
if(!$ahorroga->isDirty()) {
toast('No se detectaron cambios', 'error');
return back();
}
$ahorroga->save();
toast('Ahorro Garantia Editado', 'success');
return redirect()->route();
}
In place of using isDirty(), you can also use isClean()
if($ahorroga->isClean()) {
// some error handling here
}
isDirty means there was changes. isClean means there was no change.
Related
This question is very similar to Laravel filter a value in all columns. Sorry, if it turns out as a duplicate later on, but I have another working code to provide.
What does work is filtering on the client side via JavaScript:
filterfunction : function(entry, filter)
{
if(filter != null)
filter.trim().split(' ').forEach(function(item){
if(!this.eachRecursive(entry, item))
return false;
});
return true;
},
eachRecursive: function(obj, localfilter) {
for(const key in obj) {
if (!obj.hasOwnProperty(key))
continue;
if(typeof obj[key] == "object" && obj[key] !== null){
if(this.eachRecursive(obj[key], localfilter))
return true;
}
else
if((obj[key] + "").toLowerCase().indexOf(localfilter.toLowerCase()) != -1)
return true;
}
return false;
},
The filter function is used as the filter function for the Bootstrap-Vue table component like described in custom-filter-function.
The question is now: how to achieve similar functionality in the Laravel-Backend (for using with Livewire)?
I can imagine, that listing all columns via getColumnListing, mentioned in Laravel filter a value in all columns is possible, but this wouldn't suffice, I still need the relations, like in laravel mysql query with multiple where orwhere and inner join.
Currently, I'm trying out to convert the Eloquent object to JSON and then to parse it, as it includes all the loaded relations eloquent-serialization. But this seems like the last resort and a kind of misuse of serialization.
For now I'm going to use the route over converting to json. However, I found a way to not to parse json by regular expressions. Instead, I convert the jsonified collection back to php objects. With them I'm able to reimplement the functions from above:
private function eachRecursive(stdClass $obj, string $localfilter) {
foreach($obj as $key => $val){
if(is_object($val)){
if($this->eachRecursive($val, $localfilter))
return true;
} elseif(is_array($val)){
foreach($val as $k => $v)
if($this->eachRecursive($v, $localfilter))
return true;
} elseif(stripos(strval($val), $localfilter) !== false){
return true;
}
}
return false;
}
private function filterfunction(Collection $collection, string $filter){
$retVal = [];
foreach (json_decode($collection->toJson()) as $entity){
foreach(explode(' ', trim($filter)) as $localfilter)
if(!$this->eachRecursive($entity, $localfilter))
continue 2;
array_push($retVal, $entity->id);
}
return $retVal;
}
I'm working with Lumen framework v5.8 (it's the same as Laravel)
I have a command for read a big XML (400Mo) and update datas in database from datas in this file, this is my code :
public function handle()
{
$reader = new XMLReader();
$reader->open(storage_path('app/mesh2019.xml'));
while ($reader->read()) {
switch ($reader->nodeType) {
case (XMLREADER::ELEMENT):
if ($reader->localName === 'DescriptorRecord') {
$node = new SimpleXMLElement($reader->readOuterXML());
$meshId = $node->DescriptorUI;
$name = (string) $node->DescriptorName->String;
$conditionId = Condition::where('mesh_id', $meshId)->first();
if ($conditionId) {
ConditionTranslation::where(['condition_id' => $conditionId->id, 'locale' => 'fr'])->update(['name' => $name]);
$this->info(memory_get_usage());
}
}
}
}
}
So, I have to find in the XML each DescriptorUI element, the value corresponds to the mesh_id attribute of my class Condition.
So, with $conditionId = Condition::where('mesh_id', $meshId)->first(); I get the Condition object.
After that, I need to update a child of Condition => ConditionTranslation. So I just get the element DescriptorName and update the name field of ConditionTranslation
At the end of the script, you can see $this->info(memory_get_usage());, and when I run the command the value increases each time until the script runs very very slowly...and never ends.
How can I optimize this script ?
Thanks !
Edit : Is there a way with Laravel for preupdate multiple object, and save just one time at the end all objects ? Like the flush() method of Symfony
There is a solution with ON DUPLICATE KEY UPDATE
public function handle()
{
$reader = new XMLReader();
$reader->open(storage_path('app/mesh2019.xml'));
$keyValues = [];
while ($reader->read()) {
switch ($reader->nodeType) {
case (XMLREADER::ELEMENT):
if ($reader->localName === 'DescriptorRecord') {
$node = new SimpleXMLElement($reader->readOuterXML());
$meshId = $node->DescriptorUI;
$name = (string) $node->DescriptorName->String;
$conditionId = Condition::where('mesh_id', $meshId)->value('id');
if ($conditionId) {
$keyValues[] = "($conditionId, '".str_replace("'","\'",$name)."')";
}
}
}
}
if (count($keyValues)) {
\DB::query('INSERT into `conditions` (id, name) VALUES '.implode(', ', $keyValues).' ON DUPLICATE KEY UPDATE name = VALUES(name)');
}
}
I am learning to make caching and as I know
if(cache::has('cacheKey')) {
cache::get('cacheKey')
} else {
$data=cache::remember('cacheKey',time,function() {
return db::table('user')->get();});
return $data;
}
now question is when I am trying to search a specific data on key and then on result paginate that data for this I did use Cache::remember but how can make this fast when I am using all the time cache::remember function when I am trying to search in cache key, here is code
$page = $req->has('page') ? $req->query('page') : 1;
$keyword = $req->keyword;
if(cache::has('FileData')) {
if(!empty($keyword)) {
$file = cache::remember('FileData'.'search='.$keyword.'page='.$page,1440,function() use ($keyword) {
return File::with('callcase','lettercase','update_table','fileimages')
->where('id','Like','%'.$keyword.'%')
->orWhere('file_name','Like','%'.$keyword.'%')
->orWhere('recieved_by','Like','%'.$keyword.'%')
->orWhere('processed_by','Like','%'.$keyword.'%')
->orWhere('address','Like','%'.$keyword.'%')
->orWhere('contact_no','Like','%'.$keyword.'%')
->orWhere('show_status','Like','%'.$keyword.'%')
->orWhere('Reopen','Like','%'.$keyword.'%')
->orderBy('id','desc')
->paginate(25)
->setpath('');
});
$file->appends(['keyword'=>$keyword]);
if(count($file)>0) {
return view('home')->with('files',$file) ;
} else {
$error = "File does not found , Search another using keyword ";
return view('home')->with('filemsg',$error);
}
} else {
$file = cache::remember('FileData'.'page='.$page,1440,function () {
return File::with('callcase','lettercase','update_table','fileimages')
->orderBy('id','desc')
->paginate(25);});
return view('home')->with('files',$file) ;
}
} else {
$file = cache::remember('FileData',1440,function(){
return File::with('callcase','lettercase','update_table','fileimages')
->orderBy('id','desc')
->paginate(25);
});
return view('home')->with('files',$file);
}
My code is working fine and returning data as i wanted but i am confused on this when every time i am making remember data then how can i make that faster it would faster when i will retrieve data from already cache key and search in them and paginate them , How can i do this and help me if somehow i am doing wrong.
This is the function to update user password
function update_systemusers_password($input) {
$systemusers = users::find($input['userid']);
$systemusers->password = bcrypt($input['password']);
$systemusers->save();
}
however it doesn't update in shared hosting server
First of all you need to confirm that your function is execute or not. Try something like this to make sure.
function update_systemusers_password($input) {
dd($input); // it will show the all of input
$systemusers = users::find($input['userid']);
$systemusers->password = bcrypt($input['password']);
$systemusers->save();
}
if dd(); print all the value of request then remove the dd(); inside the function and write some condition for confirmation.
function update_systemusers_password($input) {
$systemusers = users::find($input['userid']);
$systemusers->password = bcrypt($input['password']);
if($systemusers->save()){
dd("save successfully");
}
else{
dd("found error");
}
}
While editting a product in the backend I need to know whether any of it's data has been changed or not?
$product->hasDataChanges() always return true even I didn't modify any fields.
Why does $product->hasDataChanges() always return true even I didn't modify any fields.?
Looking into the Varien_Object function setData function it appears that hasDataChanges is always set to true even if technically the data has not changes.
public function setData($key, $value=null)
{
$this->_hasDataChanges = true;
if(is_array($key)) {
$this->_data = $key;
$this->_addFullNames();
} else {
$this->_data[$key] = $value;
if (isset($this->_syncFieldsMap[$key])) {
$fullFieldName = $this->_syncFieldsMap[$key];
$this->_data[$fullFieldName] = $value;
}
}
return $this;
}
Solution:
When you have a model which is an type of Mage_Core_Model_Abstract, then you can easily get the previous data (original data) on save using public function getOrigData($key=null) method.
getOrigData() returns the data in the object at the time it was initialized/populated.
After the model is initialised you can update that data and getData() will return what you currently have in that object.
Have a look at Varien_Object (getOrigData,setOrigData) so you can have a look at how and why it is used.