generate Word document with dynamic variables using Laravel - laravel

This is the first time that I try to generate a Word document with Laravel.
I have in database columns that I should to generate in a Word document.
For example I have the following database:
I should generate a document file which contains hello John for example
So all the elements that is inside '<<>>' are a dynamic variables .
How can I get from database the value of the column preamble and set the variable name in the same time?
I found that exists a package names phpwordn but I found that I should have a template that is a word file with dynamic variables n but in my case I have no template I have all the components of my Word file in the database.
Is it possible to do that?
If you have any idea or an example to do that help me.

You can use preg_replace_callback() to convert all special tags to their corresponding values. In your case a tag has a form of <<foo>>, so here it goes:
$values = [
'me' => 'user14053977',
'saviour' => 'RoboRobok',
];
$template = 'My name is <<me>> and <<saviour>> saved me!';
$result = preg_replace_callback(
'#<<(\w+)>>#',
function (array $matches) use ($values): string {
[$tag, $tagName] = $matches;
return $values[$tagName] ?? $tag;
},
$template
);
// $result is now "My name is user14053977 and RoboRobok saved me!"
It's a pure PHP code. Now it's just the matter of using the values in Laravel and injecting $result to your Word document.

Related

Passing multiple string as parameter through url in laravel to delete specific data from database

I want to delete multiple string data that is passed by url separated by ','.
Scenario is :
http://127.0.0.1:8888/remove/lui,kui
Through this route lui and kui data that is value of name field in database will be deleted.
My web.php file
Route::get("/remove/{name}",[MyController::class,"remove"]);
MyController.php file
use App\Models\City;
function remove($name){
}
Thanks,your suggestion will be helpful.
You can accomplish this with the following:
//The string of names
$names = "cat,cat,cat,mouse,dog,rabbit";
//We break it down, seperate them by comma, then add them to an array
//After we will get the unique values only of that array
$arrayOfNames = array_unique(explode(',', $names));
//search in the name column for any of these values
//delete if found
//note that you can change the word "name" to any other column name
City::whereIn('name', $arrayOfNames)->delete();
If you have the softdelete trait in your model, and would like to hard delete its: https://laravel.com/docs/9.x/eloquent#soft-deleting
//search in the name column for any of these values
//hard delete if found
City::whereIn('name', $arrayOfNames)->forceDelete();
You can also do an update as well if that is something you are interested in the future:
//search in the name column for any of these values
//update if found
City::whereIn('name', $arrayOfNames)->update(['age' => 123, 'updated_at' => now()]);
Hope it works well for you :)

How to pass input request to foreach loop in controller to store data

I'm building a site with localizations using laravel. Trying to store names and texts in 3 languages using a form. I have a model for each article and another for article translations.
Using inputs for names and texts with input names like name_en, text_en, name_de, text_de etc...
But i can't figure out how to pass input values to a foreach loop in the store method in my controller.
I tried to pass (Request $request) object into foreach loop but it returns an error. Code is below:
public function store(Request $request)
{
$test = new Test;
$test->isActive = true;
$test->save();
//TRANSLATED INPUTS = name_tr,text_tr,name_en,text_en,name_de,text_de
foreach (['tr', 'en', 'de'] as $locale => $request)//OBVIOUSLY WRONG
{
$test->translateOrNew($locale)->name = $request->input('name_'.$locale);
$test->translateOrNew($locale)->text = $request->input('body_'.$locale);
}
$test->save();
dd($test);
//echo 'Created new article with some translations!';
}
Trying to get translated inputs itno database.
It is possible to do this the way you have it set up. You could use a series of if str contains, then str replace on name, and text, until you get the right language. But that's potentially a lot of work and likely pretty confusing if you have many names and texts coming from your form (which I assume you do from the need for a foreach on the incoming data).
I suggest you re-work your form slightly to return a bit more information. Consider the following as possible elements to return from the form:
name[]
text[]
language[]
Then, in your store method you can run through each of these in a number of ways, but to explain, I'll use the clearest (though not the most efficient):
Set an index:
$i = 0;
Run through all of the form's returns, and get the corresponding text and language that comes with the name (through the same index):
foreach($request->get('name') as $name){
$lang = $request['language'][$i];
$test->translateOrNew($lang)->name = $name;
$test->translateOrNew($lang)->text = $request['text'][$i];
$i ++;
}
This is almost pseudo code, and you will have to re-factor to make it work for you, but it should give you one idea on how you might do this. You will need to validate that the user provides each set (name, text, language) as complete, or the index will fail.

Yii2 how to get the length of translated message

In my project I am trying to provide dynamic sizing in one of my modules. I am trying to figure out in yii2 internationalization how can I get the string length of the translated text.
for instance:
<?php
//I am getting the name from the database. Assume name to be "Hello"
$name = $gettingNameFrom->db;
//Now $name is equal to string "Hello"
//The below function will dump the output to be int(5) as the length of hello is 5
var_dump(strlen($name));
//Now I want to apply translation to the above name in the db.
// I have all my translation configured and working fine.
echo Yii::t('app','{0}',[$name]);
//I have configured fo french language.
// the above output for "Hello" in french would be "Bonjour".
?>
Now how can I get the length of the translated text? I am unable to find any help online on this topic. Any help appreciated.
Thanks!!
$translated = Yii::t('app', $name);
var_dump(strlen($translated));

Code igniter with data mapper giving in valid json

I have this to select columns from a table and I want to pass this to Jquery ajax fn.
I am using below code but getting invalid json
My table has three column id, name and city but I am not selecting city
This is my json reponse
["{id:1,name\":\"JOHN\",\"city\":\"null\"}"
,"{\"id\":2,\"name\":\"MICHEAL\,\"city\":\"null\"}"]
Sadly the current stable (1.8.1) WanWizard datamapper DMZ_Json class double encode fields when you call all_to_json(). This issue seem to be fixed in the develop branch. You could workaround this multiple ways:
1. Call to_json() on individual model objects and create the json array with string manipulation:
$my_objects = (new Model)->get();
$results = array();
foreach ($my_objects as $o) {
$results[] = $o->to_json();
}
// building a json array from the strings returned by $o->to_json()
print '['.join(',', $results).']';
2. You can use the array extension's all_to_array method and json_encode that result:
$my_object_arrays = (new Model)->get()->all_to_array();
print json_encode($my_object_arrays);

Manipulate data returned from db call and then assign to template var

I'm new to smarty and prestashop. I'm building a quick, dirty module that pulls out cms pages with a particular category:
$result = Db::getInstance()->executeS('SELECT *
FROM ps_cms_lang
INNER JOIN ps_cms ON ps_cms_lang.id_cms = ps_cms.id_cms
WHERE ps_cms.id_cms_category =2
AND id_lang =1
LIMIT 0 , 30');
$smarty->assign('news', $result);
So far this is all working dandy. Thing is I want to format some of this data before I assign it to the template variable (news). How do I do this? 6 fields are returned in the $result variable. How do I get at them and do what I need (which is essentially just truncating some of the text in the description field that is returned) to do and then package them back up for the assign?
You may use $result as array, for example: $result['id_cms'].

Resources