Check if value exist in column then update the field using eloquent - eloquent

I am trying to update the data based on condition using eloquent, in my second condition i wanted to check if the db column exist color yellow then update the value to color blue if it doesn't exist then update the value to yellow. Any help please?
public function update(Request $request, Result $result)
{
Result::when($request->condition === "default", function ($query) use($result) {
$query->where('id', $result->id)
->update([
'color' => 'blue',
'confirmation' => 'Yes',
'start_date' => Carbon::now()
]);
}, function ($query) use($result) {
$query->where('id', $result->id)
->whereNotNull('start_date')
->update([
'color' => 'yellow',
'confirmation' => 'No',
'stop_date' => Carbon::now()
]);
});
return redirect()->back()->with('status', 'update');
}

Related

Laravel Backpack attribute accessor causing bug on update command

I am working on Laravel Backpack. I have two fields like this:
$this->crud->addField([ // SELECT2
'label' => 'Type',
'type' => 'select_from_array',
'name' => 'type',
'options' => [
'' => 'select type',
'Movie' => 'Movies',
'Series' => 'Series'
],
]);
$this->crud->addField([ // select2_from_ajax: 1-n relationship
'label' => "Entity", // Table column heading
'type' => 'select2_from_ajax',
'name' => 'entity_id', // the column that contains the ID of that connected entity;
'entity' => 'entity', // the method that defines the relationship in your Model
'attribute' => 'name', // foreign key attribute that is shown to user
'data_source' => url('api/entity'), // url to controller search function (with /{id} should return model)
'placeholder' => 'Select', // placeholder for the select
'include_all_form_fields' => true, //sends the other form fields along with the request so it can be filtered.
'minimum_input_length' => 0, // minimum characters to type before querying results
'dependencies' => ['type'], // when a dependency changes, this select2 is reset to null
// 'method' => 'GET', // optional - HTTP method to use for the AJAX call (GET, POST)
]);
The second field options are dependent on the first one.
In my model, I have:
public function getEntityIdAttribute()
{
$id = $this->attributes['entity_id'];
$type = $this->attributes['type'];
if ($type == "Movie") {
$attribute = Movie::find($id);
} else {
$attribute = Series::find($id);
}
return $attribute->name;
}
Create and List operations work perfectly. But on update, it throws this error:
Undefined array key "entity_id"
Why is this accessor not working on the update? or can we somehow skip the accessor on the update command?

yii2 detailview conditional row class

I would like to change class for one single attribute in detailview, based on a condition:
If I wouldn't want to make it conditional, it would be working like so:
[
'attribute' => 'ungueltig',
'format' => 'boolean',
'contentOptions' => [
'class' => 'danger',
]
],
I want this one to change to conditional, and I have tried a lot of different ways, e.g.:
[
'attribute' => 'ungueltig',
'format' => 'boolean',
'contentOptions' => function ($model) {
if ($model->ungueltig == 1) {
return ['class' => 'danger'];
} else {
return '';
}
},
],
(I would think this is the most logical solution, but nothing happens, so page is loading fine but without class danger at the attribute, no error message)
or
[
'attribute' => 'ungueltig',
'format' => 'boolean',
'contentOptions' => ['class' => function ($model) {
if ($model->ungueltig == 1) {
return 'danger';
} else {
return '';
}
},]
],
= error message: htmlspecialchars() expects parameter 1 to be string, object given
so I have no clue and I don't even find any help on the web. Can you please point me to the right direction? Many thanks!
You should simply try :
'contentOptions' => [
'class' => ($model->ungueltig == 1) ? 'danger' : '',
],
DetailView display only one model, you don't need any function here.

Handle Request: ChoicesType

So I have this ChoiceType Form that will sort the items:
$sort = $this->createForm(ChoiceType::class, NULL, array(
'choices' => array(
'...' => 'default',
'A-Z' => 'title_up',
'Z-A' => 'title_down',
'Price low to high' => 'price_up',
'Price high to low' => 'price_down',
),
));
I want to use the Choices so that when one of them is selected from the dropdown menu will do this: $products = "SELECT a FROM AppBundle:Product a ORDER BY a.title ASC".
I tried this:
$sort->handleRequest($request);
if($sort->isSubmitted() && $sort->isValid()) {
if (isset($default)) {
$products = "SELECT a FROM AppBundle:Product a ORDER BY a.title ASC";
return $this->render('AppBundle:main:index.html.twig', array('products' => $products, ));
}
}
But $default is not working, since is not defined. I dont know how to access the choices, so I can pass them to an if statement.
I think you need to write something like this:
$sort = $this->createFormBuilder()
->setAction($this->generateUrl('your_process_route_here'))
->setMethod('POST')
->add('select', ChoiceType::class, [
'placeholder' => 'Please select',
'choices' => [
'...' => 'default',
'A-Z' => 'title_up',
'Z-A' => 'title_down',
'Price low to high' => 'price_up',
'Price high to low' => 'price_down',
]
])
To get the value inside the <select> element:
$select = $request->request->get('select'); // this will contain whatever value you've selected from the dropdown
Check if the value is what you expect, and then create the query:
if ('default' == $select){ // or you can use a switch
// create a custom method inside your Repository class containing the SELECT, and call it here
}
That select from ->add('select', ...) will be the name attribute for your <select> html element.

How to sort by related table field when sending Yii2 REST GET request

I want to expand this question.
Basically I have users endpoint. But I am also returning data from the related profiles table. I am not expanding with profiles, I always want to return it. So I have fields method like this:
public function fields()
{
$fields = parent::fields();
$fields[] = 'profile';
return $fields;
}
When I do GET request and demand sorting by profile.created_at field and user.status, it does not sort by profile.created_at.
GET v1/users?sort=-profile.created_at,status
Can this be achieved somehow ?
This is my current code:
/** #var $query ActiveQuery */
$query = User::find();
// get data from profile table
$query->innerJoinWith('profile');
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => ['defaultOrder' => ['id' => SORT_DESC]],
'pagination' => [
'pageSize' => 10,
],
]);
return $dataProvider;
You have overridden 'sort' parameter of ActiveDataProvider. To keep default behaviour of Sort object and change defaultOrder property, create an instance, such as:
$sort = new \yii\data\Sort([
'attributes' => [
'profile.created_at',
],
'defaultOrder' => ['id' => SORT_DESC],
]);
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => $sort,
'pagination' => [
'pageSize' => 10,
],
]);

CakePHP 3: Migration doesn't save update data

Environment:
CakePHP 3
Postgres
I'm trying to do a migration to add a new field, then update some data for that field in our Postgres database. The entity seems to indicate that it's updated, but when I view the database, it is not saved.
Code
<?php
use Cake\Cache\Cache;
use Cake\ORM\TableRegistry;
use Migrations\AbstractMigration;
class AddDisplayRouteNumberToAgencies extends AbstractMigration
{
/**
* Up Method.
*/
public function up()
{
$table = $this->table('agencies');
$table->addColumn('display_route_number', 'boolean', [
'default' => true,
'null' => false,
]);
$table->update();
// Try to clear the Model cache
Cache::clear(null, '_cake_model_');
$patchData = [
'display_route_number' => false
];
$agencies = TableRegistry::get('Agencies');
$agency = $agencies->get(25);
// And save it back to the DB
$agencies->patchEntity($agency, $patchData);
debug($agency);
// Added after comment from ndm
$agencies->save($agency);
}
/**
* Down method
*/
public function down()
{
$table = $this->table('agencies');
$table->removeColumn('display_route_number');
$table->update();
// Clear the CakePHP Model cache
Cache::clear(null, '_cake_model_');
}
}
Results from debug()
object(App\Model\Entity\Agency) {
'id' => (int) 25,
'full_name' => 'Agency',
'legacy_agency_slug' => null,
'created' => object(Cake\I18n\Time) {
'time' => '2015-11-19T10:58:51+0000',
'timezone' => 'UTC',
'fixedNowTime' => false
},
'modified' => object(Cake\I18n\Time) {
'time' => '2015-11-19T10:58:51+0000',
'timezone' => 'UTC',
'fixedNowTime' => false
},
'display_route_number' => false,
'[new]' => false,
'[accessible]' => [
'*' => true
],
'[dirty]' => [
'display_route_number' => true
],
'[original]' => [],
'[virtual]' => [],
'[errors]' => [],
'[repository]' => 'Agencies'
}
Postgres query and results
SELECT id, display_route_number
FROM agencies
WHERE id = 25;
id | display_route_number
----+----------------------
25 | t
(1 row)
Other attempts
I also tried just using save() rather than patchEntities(), which returned the same results, except [dirty] is empty.
$agencies = TableRegistry::get('Agencies');
$agency = $agencies->get(25);
// Items to update
$agency->display_route_number = false;
// And save it back to the DB
$agencies->save($agency);
Thanks to #ndm for figuring this out for me. I ended up having to update the table schema. I believe this is because the Migration table part updates the SQL, but doesn't update the Schema.
Here's the final code:
// Clear the CakePHP Model cache
Cache::clear(null, '_cake_model_');
$table = $this->table('agencies');
$table->addColumn('display_route_number', 'boolean', [
'default' => true,
'null' => false,
]);
$table->update();
$agencies = TableRegistry::get('Agencies');
// REQUIRED!! Add the field to the Table schema
$agencies->schema()->addColumn('display_route_number', [
'type' => 'boolean',
'default' => true,
'null' => false
]);
$agency = $agencies->find()
->where(['short_name' => 'bart'])
->first();
// Items to update
$agency->display_route_number = false;
// And save it back to the DB
$agencies->save($agency);