How to update only one property of model? - laravel

I'm working on user consents. In my request I have these properties:
$newsLetters (bool|nullable),
$sms (bool|nullable),
$billEmail (bool|nullable),
I need update only one. So I need to find one which is not null and update it, if in my request is more than one properties with bool values i need to throw exception.
How can I achieve this?
My request extends spatie/laravel-data.

I don't understand why would you handle something like this on the backend (you can use radio button for this and always send only one value), you can use validation for requests or something like this:
$newsLetters = null;
$sms = true;
$billEmail = null;
$values = [$newsLetters, $sms, $billEmail];
$filter = sizeof(array_filter($values, function($el) { return $el === null;})) < 2;
if($filter) {
//return exception or whatever
} else {
//update values
}

Related

gettin request/query parameters with less code

Is this:
$paginate = $request->get('paginate');
Equivalent to this, for getting a query param if it is present or assign to the associated variable "null" it it is not present:
if ($request->has('paginate')) {
$paginate = $request->get('paginate');
} else {
$paginate=null;
}
According to get() method documentation:
This method belongs to Symfony HttpFoundation and is not usually needed when using Laravel.
Alternatively you can use filled and $request->paginate
So it checks if the request has the "item"and it has value.
$paginate = null;
if ($request->filled('paginate')){
$paginate = $request->paginate;
}

Call to a member function update() on null with array/checkbox/edit

Need help here i m trying to take values from checkbox s and put them into a edit to change the value "Estado" to "Expedido" but when I run the code it gives me the error"Call to a member function update() on null".I also tried find and change the default of find() to the column i want and also tried with raw postgresql code.
$chassis= $request->chassis;
$escala = $request->escala;
if(Auth::check() == true)
{
foreach($chassis as $chassis)
{
$edit = expedicoes::whereIn('Chassis', explode(',',$chassis))->first()->update(['Estado' =>'Expedido']);
}
The method update(Array) doesnt exist on a model instance, it only exists on a query builder as a Builder instance.
either remove the first() call to call update on the query builder
$edit = expedicoes::whereIn('Chassis', explode(',',$chassis))->update(['Estado' =>'Expedido']);
Or update the on the model then call save()
$edit = expedicoes::whereIn('Chassis', explode(',',$chassis))->first();
if ($edit) {
$edit->Estado = 'Expedido';
$edit->save();
}
I suggest you remove the update call from the foreach loop, gather all "chassis" and run a single query
$extractedChassis = [];
foreach($chassis as $chassi)
{
$extractedChassis = array_merge($extractedChassis , explode(',',$chassi));
}
expedicoes::whereIn('Chassis', $extractedChassis)->update(['Estado' =>'Expedido']);
this code return null
expedicoes::whereIn('Chassis', explode(',',$chassis))->first()
so you have no items that Chassis in explode(',',$chassis)
to solve this you can check if its not return null then update it
$expedicoes = expedicoes::whereIn('Chassis', explode(',',$chassis))->first();
if(expedicoes ){
expedicoes ->update(['Estado' =>'Expedido']);
}
but i think your problem in column name so try to use chassis instead of Chassis
and estado instead of Estado

Api platform add or update

Good afternoon I am adding data in via POST method in PLATFORM API can I make this method work like adding or updating data.
So that when the data is already there for the object, it will simply update the pinOrder field.
My input:
{
"chat": "/api/chats/01FVKRYXMMTHKJ2EZB02F4FZ3Z",
"pinOrder": 3
}
Insert or update (upsert) is not available in Api Platform. However, you can achieve this behavior with a custom (or decorated) Data Persister.
https://api-platform.com/docs/core/data-persisters/
In the persist method of the data persister you could manually check if an item matching your criteria does already exist and, if yes, update this one instead of persisting a new one.
You can use PRE_WRITE event. For exemple, an order item quantity.
public static function getSubscribedEvents(): array
{
return [
KernelEvents::VIEW => [
'updateExistingItemQuantity', EventPriorities::PRE_WRITE,
],
];
}
public function updateExistingItemQuantity(
ViewEvent $event
): void {
$item = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (!$item instanceof MyItemObject || Request::METHOD_POST !== $method) {
return;
}
// find duplicateItem
if ($duplicateItem) {
$duplicateItem->setQuantity("UPDATED QUANTITY");
// save $duplicateItem
$event->setControllerResult($duplicateItem);
}
}

Set ModelState Based on Server Side Query Result in MVC5

I have a query that tests for a valid postcode entry:
using (_ctx)
{
try
{
var pc = _ctx.tblPostcodes.Where(z => z.Postcode == postcodeOutward)
.Select(x => new { postcodeId = x.PostcodeID }).Single();
pcId = pc.postcodeId;
}
catch (Exception)
{
pcId = 0;
Response.Redirect("./");
}
}
I don't like how I've done it. It's clumsy and it doesn't show an error (this is my first MVC project).
I'd rather it return a validation error against the Postcode textbox. I have model annotations for various input mistakes, but have to check the postcode against the database.
Any suggestions on how to set ModelState to get a proper response?
You could try:
if(this.ModelState.ContainsKey("postcodeOutward"))
this.ModelState.Add("postcodeOutward", new ModelState());
ModelState state = this.ModelState["postcodeOutward"];
state.Errors.Add("<error_message>");
state.Value = new ValueProviderResult(postcodeOutward, postcodeOutward == null ? "" : postcodeOutward.ToString(), CultureInfo.CurrentCulture);
You could also try having a custom validation attribute that will perform a check against the database and that should automatically populated the this.ModelState property, but I'm not too sure if accessing the database inside of a validation attribute would be a good/recommened approach to take.

How to get Response of REST API in JSON format by Default in Magento

In magento as we use the REST url to access the data,as http://localhost/magemto/api/rest/products it returns in XML format.
But as my team requirement, I should send the data in JSON format to access AJAX calls easily.. I have used REST client to include a header as 'Content-Type:appilcation/json'.. Then it returns in JSON format.. But I want it as defaultly by the magento API..
Hey, I do have a solution for this, I would like to share with you.
First go to your magento root folder then go to following path
\app\code\core\Mage\Api2\Model\Request.php
Go to the method getAccepTypes() and change with this code below it will fulfill your requirement.
public function getAcceptTypes()
{
$qualityToTypes = array();
$orderedTypes = array();
foreach (preg_split('/,\s*/', $this->getHeader('Accept')) as $definition) {
$typeWithQ = explode(';', $definition);
$mimeType = trim(array_shift($typeWithQ));
// check MIME type validity
if (!preg_match('~^([0-9a-z*+\-]+)(?:/([0-9a-z*+\-\.]+))?$~i', $mimeType)) {
continue;
}
$quality = '1.0'; // default value for quality
if ($typeWithQ) {
$qAndValue = explode('=', $typeWithQ[0]);
if (2 == count($qAndValue)) {
$quality = $qAndValue[1];
}
}
$qualityToTypes[$quality][$mimeType] = true;
}
krsort($qualityToTypes);
foreach ($qualityToTypes as $typeList) {
$orderedTypes += $typeList;
}
unset($orderedTypes);
$orderedTypes=Array
("application/json" => 1);
return array_keys($orderedTypes);
}
Hope this help you.

Resources