Laravel 5.5 - Check if only one column will be updated - laravel

Using Laravel 5.5 and models, I would like to know, before updated if only one column, statut, will be updated.
The interest is to just updated the statut if there are no changes or, if there are some columns to be updated, create a new row. Because each modification need to be approved before published.
Actually, I have a big if like :
if($request->statut != $product->statut && $request->title == $product ...)
Is there a quickest way ?
Thanks.

You can utilize isDirty('field') method to check if the field was changed (and not yet saved). getDirty() will return you array of all such fields and their values.
If I understood your case correctly, then you can do:
if ($product->isDirty('statut')) {
if (count($product->getDirty()) == 1) {
...
}
}
First we check if field statut was changed for your $product. Then we just check if number of changed fields is 1 (meaning that there are no more changed fields than just statut).

Related

Laravel Choosing one column in database conditionally

I have a 2 columns in one of my table.
| mark_1 | mark_2 |
These marks are saved for 2 types of users in the system.
mark_1 is for user_type_1
mark_2 is for user_type_2
When fetching from this table, I need to conditionally get specific mark column (mark_1 or mark_2) as mark for each type of user. How to achieve this using Laravel eloquent model.
But want this in Eloquent such as when I query Mark::all() I need the necessary mark column value.
if($userType == 'student_1'){
$marks = DB::table('marks')
->select('user_id', DB::raw('marks_1 as marks'));
} else {
$marks = DB::table('marks')
->select('user_id', DB::raw('marks_2 as marks'));
}
use 'addSelect' statement:
$query=User::query()->select('id');
if($userType == 'student_1')
$query=$query->addSelect('marks_1 as marks');
else
$query=$query->addSelect('marks_2 as marks');
$marks=$query->get();
more details about 'addSelect' in here:
https://laravel.com/docs/7.x/eloquent#advanced-subqueries
You can use Accessors & Mutators to get specify column value depend condition or append new attribubte to your model
check this link:
https://laravel.com/docs/7.x/eloquent-mutators#accessors-and-mutators

Laravel, Get row with highest version column from database

At the moment i have a 1 to many relationship between 2 models. A Machine model and a Document Model.
A document can have multiple versions and i always related to my machine. Now i only want to show the documents with the latest or highest version.
I've tried to get the version from the document but then i can only return 1 document to my view instead of returning multiple documents. I've also tried to get the documents the following way but i get stuck with the steps i need to take after creating the loop:
$machine = Machine::find($id);
$documents = $machine->documents;
foreach($documents as $document)
{
}
dd($documents);
return view('machine.detail', compact('machine'));
So to specify my question: How can i return only the unique documents with the latest version to my view. So if file 1 has versions 1,2,3,10 and file 2 has versions 1,2,3 i want to return version 10 of file 1 and version 3 of file 2.
If I understand your question correctly you can do the following.
// Add this relation also on your model where your hasMany is on properly Machine.php
public function latestDocument()
{
return $this->hasOne(Document::class)
->latest('version_column');
}
// Controller
$machine = Machine::with(['latestDocument'])->findOrFail($id);
$document = $machine->latestDocument;
return view('machine.detail', compact('machine'));
If you have a unique key for each document that is shared for all the versions something like this should work.
$documents = $machine->documents->groupBy('name of your unique key')->map(function($documents) {
$latestVersion = $documents->max('version');
return $documents->firstWhere('version', $latestVersion);
});
Explanation: The get the latest version from each document we first need to group all documents by a key to separate all the unqiue documents into multiple collections that contain the versions.
Then we need to map them into a new collection where we only get the document with the latest version.
Note: Dont forget to change $machine = Machine::find($id); to $machine = Machine::with('documents')->find($id); so you load the documents before hand. This will prevent the n+1 query problem

How to check values before update in Eloquent?

When using updating via Eloquent it returns affected rows as a result. Is it possible somehow to get status of update? For example if I passing some bad id in WHERE it still return 0 affected rows, though here I need to know that this id does not exist. Basically when the user clicks a save button, but nothing edit - I get 0 affected rows from Eloquent and also when bad id is entered. I need to somehow separate this things.
You could check first if the WHERE returns anything:
if(Model::where($where)->count() > 0){
// row(s) found > do update
}
else {
// where doesn't match any rows
}

Query using EF "Include" and including the related tables on Where

So far, I thought I could do:
var num = db.MyTable.Include(x => x.RelatedTable)
.Count( x.idTenant == CurrentTenantID && x.Active &&
x.RelatedTable.SomeProperty.Value == true);
This always return zero records.
Am I assuming wrongly that Including the RelatedTable I can use it in the where part?
By the way... the "SomeProperty" is Nullable, that is why the ".Value".
I'm using Entity Framework 4.1. (Database first)
Are you trying to get the number of records? If so, why do you even need the Include? Entity Framework will lazy-load the RelatedTable entity set for you when it evaluates your Count condition. Also, if SomeProperty is a bool?, you should check if it has a value before you check the value itself.
var num = db.MyTable.Count(x =>
x.idTenant == CurrentTenantID &&
x.Active &&
(x.RelatedTable.SomeProperty.HasValue &&
x.RelatedTable.SomeProperty.Value));
You don't need to use Include if you only want to access navigation property in Where part. Include is only used to fetch (eager load) related records together with the main record from database to your application but it doesn't make sense if you only want to count records.

Doctrine Email Validation triggers on empty form field

I don't want an empty email field in my form to trigger a
Doctrine_Validator_Exception. But, since Doctrine_Validator_Email uses
"is_null()" to check for empty (non-existing) values (and the POST
['email'] contains an empty string), it does.
Is this correct? Is there a simple way around this?
This also has an impact when trying to set a column as unique (trying
to store a second empty string in the column triggers the validator).
What am I missing?
Thanks in advance,
Erland Wiencke
(Symfony 1.4.1/Doctrine 1.2)
I ran into this same problem in our Doctrine 1.2 application. In my case, the fix ended up adding this workaround to the record's merge() method:
$this->email = trim($this->email);
if ($this->email == '') {
$this->email = null;
}
There are several ways, not tested, but seem to work alltogether or separately:
1) $this->validatorSchema['email'] = null;
or
2) $this->validatorSchema['email'] = sfValidatorPass();
or
3) $this->validatorSchema->setOption('allow_extra_fields', true);
or
4) Just set required attribute to false:
$this->widgetSchema['email'] = sfWidgetFormInputText(array('required' => false));

Resources