How to generate fpdf? - laravel-5.4

I am getting error 'Class "Fpdf" not found'.
use Fpdf;
Fpdf::AddPage();
Fpdf::SetFont('Courier', 'B', 18);
Fpdf::Cell(50, 25, 'Hello World!');
Fpdf::Output();

Install using Composercomposer require codedge/laravel-fpdf
Add the following lines to your config/app.php
'providers' => [
// ...
Codedge\Fpdf\FpdfServiceProvider::class,
],
'aliases' => [
// ...
'Fpdf' => Codedge\Fpdf\Facades\Fpdf::class,
]
Use it (omit use Fpdf):
Fpdf::AddPage();
Fpdf::SetFont('Courier', 'B', 18);
Fpdf::Cell(50, 25, 'Hello World!');
Fpdf::Output();
or
$fpdf = new Codedge\Fpdf\Fpdf\Fpdf();
$fpdf->AddPage();
$fpdf->SetFont('Courier', 'B', 18);
$fpdf->Cell(50, 25, 'Hello World!');
$fpdf->Output();

Related

json file is overwritten entirely when trying to add an object in laravel

I am trying to insert a JSON object in a JSON file (.json is located in the storage/app folder).
But it's replacing all the previous data. My code from the controller is:
public function editjson() {
$jsonString = \Illuminate\Support\Facades\Storage::get("test.json");
$data = json_decode($jsonString, true);
$extra = array(
'id' => 2,
'product_name' => 'Banana',
'per_item_price' => '50',
'product_quanity'=> '4',
'total_price' => '50'
);
$array_data[] = $extra;
$newJsonString = json_encode($array_data);
file_put_contents("../storage/app/test.json", $newJsonString);
}
Update same array which is retrieved from the json file:
$jsonString = \Illuminate\Support\Facades\Storage::get("test.json");
$data = json_decode($jsonString, true);
$extra = [
'id' => 2,
'product_name' => 'Banana',
'per_item_price' => '50',
'product_quanity' => '4',
'total_price' => '50'
];
$data[] = $extra;
$newJsonString = json_encode($data);
file_put_contents("../storage/app/test.json", $newJsonString);
Updated
Instead of using file_put_contents.you can use Storage::disk
Storage::disk('local')->put("test.json",json_encode($newJsonString));

Laravel Attach Files Duplicates Database Record

I am using: Laravel, Vue JS, dropzone.
Works fine with one file being uploaded but when 3 files are uploaded it create a new homework record, like so:
Homework ID: 1, Files: 1, 2
Homework ID: 2, Files: 3
Should look like:
Homework ID: 1, Files: 1,2,3
Code for upload is the following:
public function store() {
$data = request()->validate([
'title' => '',
'description' => '',
'start_date' => '',
'due_date' => '',
'group_id' => '',
'dropzonefile' => '',
'live_status' => '',
]);
// Create homework record...
$task = request()->user()->homeworks()->create([
'title' => $data['title'],
'description' => $data['description'],
'start_date' => $data['start_date'],
'due_date' => $data['due_date'],
'live_status' => $data['live_status'],
]);
// Add homework to some groups...
$task->groups()->attach(Arr::pluck(json_decode($data['group_id']), 'group_id'));
// Upload all files...
if (isset($data['dropzonefile'])) {
foreach ($data['dropzonefile'] as $attachment) {
$attachmentName = $attachment->store('userFiles', 'public');
$attachmentInfo = request()->user()->attachments()->create([
'reference_name' => $attachmentName,
'original_file_name' => $attachment->getClientOriginalName(),
]);
$task->attachments()->attach($attachmentInfo->id);
}
}
return new TaskResource($task);
}
Front End Code:
dropzoneOptions: {
paramName: "dropzonefile",
url: '/api/homework',
thumbnailWidth: 150,
maxFilesize: 20,
maxFiles: 5,
addRemoveLinks: true,
uploadMultiple: true,
autoProcessQueue: false,
headers: {
'X-CSRF-TOKEN': document.head.querySelector('meta[name=csrf-token]').content,
},
sending: (file, xhr, formData) => {
formData.append('title', this.taskTitle);
formData.append('description', this.content);
formData.append('start_date', this.selectedSetDate);
formData.append('due_date', this.selectedDueDate);
formData.append('group_id', JSON.stringify(this.value));
formData.append('live_status', this.liveStatus);
},
success: (event, res) => {
// alert('success');
console.log(event);
this.makeToast(true,'info');
this.$router.push('/Teacher')
}
},
I think I found the answer:
upload multiple files in one request Dropzone sending two requests
Seems like I was missing some dropzone options:
autoDiscover: false,
parallelUploads: 10,

How to work with dates using node js model and mysql

I'm working in a project that uses nodejs API and mysql as database.
I need to make a query that returns all the data of the current month and another one that returns all data between a period.
To get all records, I'm doing this
ContractValue.findAll({
where: {
data: id
},
order: [['data', 'ASC']]
})
The thing is I don't know how to put the conditions inside the where clause
This seems like you are using "Sequelize" as your ORM and from your question i can tell that the problem is that you don't know how to put where conditions.
This should help you!
ContractValue.findAll({
where: {
id: {
[Op.and]: {a: 5}, // AND (a = 5)
[Op.or]: [{a: 5}, {a: 6}], // (a = 5 OR a = 6)
[Op.gt]: 6, // id > 6
[Op.gte]: 6, // id >= 6
[Op.lt]: 10, // id < 10
[Op.lte]: 10, // id <= 10
[Op.ne]: 20, // id != 20
[Op.between]: [6, 10], // BETWEEN 6 AND 10
[Op.notBetween]: [11, 15], // NOT BETWEEN 11 AND 15
[Op.in]: [1, 2], // IN [1, 2]
[Op.notIn]: [1, 2], // NOT IN [1, 2]
[Op.like]: '%hat', // LIKE '%hat'
[Op.notLike]: '%hat', // NOT LIKE '%hat'
[Op.iLike]: '%hat', // ILIKE '%hat' (case insensitive) (PG only)
[Op.notILike]: '%hat', // NOT ILIKE '%hat' (PG only)
[Op.overlap]: [1, 2], // && [1, 2] (PG array overlap operator)
[Op.contains]: [1, 2], // #> [1, 2] (PG array contains operator)
[Op.contained]: [1, 2], // <# [1, 2] (PG array contained by operator)
[Op.any]: [2,3] // ANY ARRAY[2, 3]::INTEGER (PG only)
},
status: {
[Op.not]: false // status NOT FALSE
}
}
})
You can read more on the documentation (https://sequelize.org/master/manual/models-usage.html) and also you should really know the tools you are using.
There is node module for working with mysql database,first you create mysql connection object:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});
connection.connect();
then you can build your desired query with it:
connection.query('SELECT * FROM table WHERE 'YOU CONDITIONS...', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
connection.end();
ContractValue.findAll({
where: {
data: {
[Op.between]: [start, end]
}
},
order: [
['data', 'ASC']
]
})

How to add new values to multiple Select2 from Kartik instead of replace old ones?

I use Select2 widget in multiply mode in YII2 framework. "kartik-v/yii2-widget-select2": "#dev" - this one I have downloaded via composer.
kartik-v/yii2-widget-select2 dev-master dd09e46
I added initial values with ajax on widget init ('initSelection'). And added another ajax method to suggest new values on user's typing. When user select one from list, it replaced initial values what were added on init. New values replace initial values, but don't another new.
I want new values to add to initial instead of replace it.
<?= $form->field($model, 'security[]')->widget(Select2::class, [
'attribute' => 'security',
'hideSearch' => true,
'data'=>$security_data,
'options' => [
'placeholder' => 'Security',
'multiple' => true,
],
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 1,
'ajax' => [
'url' => Url::toRoute([ '/admin/security/select-items' ]),
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }'),
'results' => new JsExpression('function(data,page) { return {results:data.results}; }'),
],
'initSelection' => new JsExpression('function(element, callback) { var id = '.Yii::$app->request->getQueryParams()['id'].';if(id !== "") {$.ajax("' . \yii\helpers\Url::toRoute([ '/admin/security/init-items' ]) . '", {data: {id: id},dataType: "json"}).done(function(data) {callback(data.results);});}}'),
],
]); ?>
And here is my api methods:
public function actionSelectItems($q = null){
Yii::$app->response->format = Response::FORMAT_JSON;
$out = ['results' => []];
if(!empty($q)){
$items = Security::find()->where(['like', 'title', $q])->all();
foreach ($items as $item){
$out['results'][] = ['id'=>$item->id, 'text'=>$item->title];
}
}
return $out;
}
public function actionInitItems($id = null){
Yii::$app->response->format = Response::FORMAT_JSON;
$adv = Adv::findOne($id);
$security = #json_decode($adv->security, true);
$out = ['results' => []];
foreach ($security as $item){
$text = Security::findOne($item)->title;
$out['results'][] = ['id'=>$item, 'text'=>$text];
}
return $out;
}
Is there some sort of settings or I missed something when handle http result?

JSON sort by specific value - PERL

i have this example code
#!/usr/bin/perl
use strict;
use warnings;
use JSON::PP qw( );
use Data::Dumper qw (Dumper);
my $json = JSON::PP->new()->pretty->utf8; # lesbares JSON | Sort numerically
my %ORDER = (id => 1, name => 2);
$json->sort_by(sub {
($ORDER{$JSON::PP::a} // 999) <=> ($ORDER{$JSON::PP::b} // 999)
or $JSON::PP::a cmp $JSON::PP::b
});
print $json->encode(
[
{name => 'ABS700', id => 0, data => [
{
dmsg => 's4F038300', state => 'T: 3.3', user => 'SD_Protocol'
}
]
},
{name => 'GT-WT-02', id => 0, data => [
{
dmsg => 's5410AC5F9800', state => 'T: 17.2 H: 47', user => 'Ralf9'
}
]
},
{name => 'NEU', id => 99, data => [
{
dmsg => 's5410AC5F9800', state => 'T: 17.2 H: 47', user => 'NEUER'
}
]
},
{name => 'Ventus W132', id => 4, data => [
{
dmsg => 'sD66EE1603000', user1 => 'dirigent', comment => 'wind',
readings => [{ state => 'windGuest: 1.2 winddir:0' }]
}
]
},
],
);
I would like to sort this, that the value with the "id => 99" appears at the end.
I could sort all internal values ​​arbitrarily but I need the new outer sorting.
How do I solve this problem?
->sort_by is used to control the order of the elements of hashes.
You want to control the order of the elements of an array.
There's no equivalent mechanism to ->sort_by for arrays because there's no need for one. While you can't naturally control the order in which a hash returns its elements, you can naturally control the order in which an array returns its elements.
my $data = [ ... ];
#$data = sort { $a->{id} <=> $b->{id} } #$data;
print $json->encode($data);