Laravel eloquent add to JSON - mysql

To begin with, sorry for my bad English. I have column:
$table->json('images')->nullable();
Table is called albums. In images I would like to store an array with image names, but how can I every time add to that json? My code right now:
$album = Album::where('hash', $request->album_hash)->firstOrFail();
$album->update([
'images' => $request->image->name <= tried to do something.. My uploader everytime calls this function, so I need to get current IMAGES column value, and add new. Like ['first image name', 'second image name'], after update this must be ['first image name', 'second image name', 'third image name'] not just ['third image name']
]);
$album->save();
I need to do like laravel increment function, but which works only with int looks like. How can I do that? Thanks in advance!

I think its not possible to directly change the JSON as your images data would return as a String.
First get the JSON as a string, then update the Object and update the JSON.
So something like:
$album = Album::where('hash', $request->album_hash)->firstOrFail();
$images = json_decode($album->images);
array_push($images, $request->image->name);
$album->update(['images' => $images]);
$album->save();
Note: I didn't check this code, but this should give you an idea of how to handle this
Good luck

$album = Album::where('hash', $request->album_hash)->firstOrFail();
$arra = json_decode($album->images);
$arra[] = $request->image->name;
$album->update([
'images' => $arra
]);
$album->save();
I hope help you

Related

CakePHP 4 do not get new added fields from DB

I have some trouble getting content of a new created field from Database.
At the beginning i created my "Menue" table in phpmyadmin and then in cake with "bin/cake bake all Menue". So far so good. But i forgot a field "price" which i added right now in the database and filled it with content.
In cake i added this field "price" in src/Model/Entitiy/Menue and src/Table/MenuesTable.php. In the Controller src/Controller/MenuesController i wanted to get the price with $menue->price but there is no field key or content. Also print_r($menue); return all other fields and content but not the price field.
is there another file where i have to add this field?
In phpmyadmin i can do a simple sql statement and i get this field with content in the results... so i am thinking cake is missing something.
Thanks in advance!
The following query was created by the bake command.
$menue = $this->Menues->get($id, [
'contain' => ['Restaurants'],
]);
also a self written query do do deliver the field "price"
$menue = $this->Menues
->find()
->where(['id ='=>$id]);
foreach($menue as $m){
print_r($m);
}
I just figured out, that this field and a again newly created "test" field are loaded in another Controller written by hand with
$this->loadModel('Menues');
...
$contents = $this->Menues
->find()
->select(['id',
'title',
'short_description',
'additives',
'price',
'currency',
'image_path'
'test'
])
->where(['restaurant_id =' => $restaurant_id,'menuegroup' => $cat['menuegroup']])
->order(['sort_order' => 'ASC']);
But why my other controller do not want to give me the price is still a question i can not answer. maybe someone knows.
THX

How can I have the name of my entity instead of the id in the related tables

I'm creating a project on CakePHP 3.x where I'm quite new. I'm having trouble with the hasMany related tables to get the name of my entities instead of their ids.
I'm coming from CakePHP 2.x where I used an App::import('controller', array('Users') but in the view to retrieve all data to display instead of the ids, which is said to be a bad practice. And I wouldn't like to have any code violation in my new code. Can anybody help me? here is the code :
public function view($id = null)
{
$this->loadModel('Users');
$relatedUser = $this->Users->find()
->select(['Users.id', 'Users.email'])
->where(['Users.id'=>$id]);
$program = $this->Programs->get($id, [
'contain' => ['Users', 'ProgramSteps', 'Workshops']
]);
$this->set(compact('program', 'users'));
$this->set('_serialize', ['ast', 'relatedUser']);
}
I expect to get the user's email in the relatedUsers of the program table but the actual output is:
Notice (8): Trying to get property 'user_email' of non-object [APP/Template\Asts\view.ctp, line 601].
Really need help
Thank you in advance.
You've asked it to serialize the relatedUser variable, but that's for JSON and XML views. You haven't actually set the relatedUser variable for the view:
$this->set(compact('program', 'users', 'relatedUser'));
Also, you're setting the $users variable here, but it's never been initialized.
In addition to #Greg's answers, the variable $relateduser is still a query object, meaning that trying to access the email property will fail. The query still needs to be executed first.
You can change the query to:
$relatedUser = $this->Users->find()
->select(['Users.id', 'Users.email'])
->where(['Users.id' => $id])
->first();
Now the query is executed and the only the first entry is returned.
There is are a number of ways to get a query to execute, a lot of them are implicit is use. See:
Cookbook > Retrieving Data & Results Sets

Transactional Emails - Default Styling and Variables in Magento 1.9

I'm looking for 2 specific variables.
Wishlist - The var_message variable has some styling to it that im trying to edit.
Abandoned Carts - pulls on this extension URL : connector/email/basket/code/secret/quote_id/*****
And im unable to find the location of the file that is accessed by that URL or command.
Any assistance that can be provided would be greatly appreciated.
Also if someone could tell me how i might trace the locations of these things without "Just knowing" that would be grand too.
Kind Regards,
the correct variable name is message (not var_message)
variable message is populated in controller Mage_Wishlist_IndexController
inside method sendAction
here it is:
$emailModel = Mage::getModel('core/email_template');
$sharingCode = $wishlist->getSharingCode();
foreach ($emails as $email) {
$emailModel->sendTransactional(
Mage::getStoreConfig('wishlist/email/email_template'),
Mage::getStoreConfig('wishlist/email/email_identity'),
$email,
null,
array(
'customer' => $customer,
'salable' => $wishlist->isSalable() ? 'yes' : '',
'items' => $wishlistBlock,
'addAllLink' => Mage::getUrl('*/shared/allcart', array('code' => $sharingCode)),
'viewOnSiteLink' => Mage::getUrl('*/shared/index', array('code' => $sharingCode)),
'message' => $message
)
);
}
$wishlist->setShared(1);
$wishlist->save();
and the actual content of the message comes from a form input and gets fetched over here:
$message = nl2br(htmlspecialchars((string) $this->getRequest()->getPost('message')));
there is no actual styling or css assigned to it. In fact most of styles are defined inline in email templates

Creating URL and params in Yii2

I'm trying to create Url with multiple param using Url::to() method but it's not working i also tried UrlManager->creatUrl() method but no luck, i have pretty Url enable and if i use only one query param it works fine but when i try to add more i got error, below is my code.
$linkUrl = \Yii::$app->UrlManager->createUrl(['sell/updatecategory', ['draftId'=> $model->draftId,'catid' =>$model->category_id]]);
<?= Html::button('Change category or product',['value'=>$linkUrl, 'id' => 'StartOver']) ?>
another try is:
$linkUrl = Url::to(['sell/updatecategory', ['draftId'=> $model->draftId,'catid' =>$model->category_id]]);
in the two case above the url output always look like this:
GET http://http://192.168.199.128/trobay/products/sell/updatecategory?1%5BdraftId%5D=20&1%5Bcatid%5D=50
and the server throw an error cannot resolve the url, what i want is something like this:
GET http://http://192.168.199.128/trobay/products/sell/updatecategory?draftId=20&catid=50
The system added some character which i guess is the cause of the problem but don't really know how to remove this. i hot anyone could help with this thanks
Don't use nested array for parameters.
Structure should look like this:
[0 => route, param1 => value1, param2 => value2, ...]
so in your case
$linkUrl = Url::to([
'sell/updatecategory',
'draftId' => $model->draftId,
'catid' => $model->category_id
]);

Laravel Fluent queries - How do I perform a 'SELECT AS' using Fluent?

I have a query to select all the rows from the hire table and display them in a random order.
DB::table('hire_bikes')->order_by(\DB::raw('RAND()'))->get();
I now want to be able to put
concat(SUBSTRING_INDEX(description, " ",25), "...") AS description
into the SELECT part of the query, so that I can select * from the table and a shortened description.
I know this is possible by running a raw query, but I was hoping to be able to do this using Fluent or at least partial Fluent (like above).
How can I do it?
You can actually use select AS without using DB::raw(). Just pass in an array into the select() method like so:
$event = Events::select(['name AS title', 'description AS content'])->first();
// Or just pass multiple parameters
$event = Events::select('name AS title', 'description AS Content');
$event->title;
$event->content;
I tested it.
Also, I'd suggest against using a DB:raw() query to perform a concatenation of your description field. If you're using an eloquent model, you can use accessors and mutators to perform this for you so if you ever need a limited description, you can simply output it in your view and not have to use the same query every time to get a limited description. For example:
class Book extends Eloquent
{
public function getLimitedDescriptionAttribute()
{
return str_limit($this->attributes['description'], $limit = 100, $end = '...');
}
}
In your view:
#foreach($books as $book)
{{ $book->limited_description }}
#endforeach
Example Output (not accurate to limit):
The description of this book is...
I'd also advise against using the DB facade because it always utilizes your default connection. If you're querying a secondary connection, it won't take this into account unless you actively specify it using:
DB::connection('secondary')->table('hire_bikes')->select(['name as title'])->get();
Just to note, if you use a select AS (name AS title) and you wish to update your the model, you will still have to set the proper attribute name that coincides with your database column.
For example, this will cause an exception because the title column does not exist in your database table:
$event = Events::select('name AS title')->first();
$event->title = 'New name';
$event->save(); // Generates exception, 'title' column does not exist.
You can do this by adding a DB::raw() to a select an array in your fluent query. I tested this locally and it works fine.
DB::table('hire_bikes')
->select(
array(
'title',
'url',
'image',
DB::raw('concat(SUBSTRING_INDEX(description, " ",25),"...") AS description'),
'category'
)
)
->order_by(\DB::raw('RAND()'))
->get();
select(array(DB::raw('latitude as lat'), DB::raw('longitude as lon')))