Laravel excel, iterate item to insert data - excel

My excel file consists of student id, name, and course which i'm saving in database. The data was separated by gender in which at row[0]. what i'm trying to achieve here is how can i iterate my data and insert a gender in my database.?
Sample sample.xlsx
//StudentController
Excel::import(new StudentsImport, request()->file('import'));
//ImportSheet
public function model(array $row)
{
//empty rows
if (!isset($row[1]) || $row[0] == '#') {
return null;
}
if (isset($row[1])) {
return new Student([
'id_number' => $row[1],
'name' => $row[2],
'course' => $row[3],
'gender' => 'male || female', //<--- HOW CAN I INSERT GENDER HERE BASE ON THE JPEG ABOVE?
]);
}
}

Here is the way this may help you to get your gender:
public function model(array $row)
{
//empty rows
if (!isset($row[1]) || $row[0] == '#') {
return null;
}
//get the gender
$gender = ''; // default is empty, you can also assign some default value
if (isset($row[0]) && (strtolower($row[0]) == 'male' || strtolower($row[0]) == 'female')) {
$gender = $row[0];
}
if (isset($row[1])) {
return new Student([
'id_number' => $row[1],
'name' => $row[2],
'course' => $row[3],
'gender' => $gender
]);
}
}

Related

How to check multiconditions to concatenate an observable with rxjs

I would like to make check condition on message which is an observable and to costumize the output like this scenerio :
check if the messsage is to me or from me and concatenate 20 first caracters with the name of friend or if it is my message with you
chech the type of message if it is a photo or file to make a message you sent an attament for example
getLastMessage(onlineUserModel: OnlineUserModel): Observable<string> {
let message: Observable<string>;
const messageModel = this.allDirectMessages$
.pipe(
map((x) =>
x.filter(
(f) =>
f.messageModel.to.userName === onlineUserModel.userName ||
f.messageModel.from.userName === onlineUserModel.userName
)
)
)
.pipe(map((data) => data[data.length - 1].messageModel))
.pipe(
map((item) => {
if (item.to.userName == onlineUserModel.userName) {
message = concat("You", item.content, "...");
}
else (item.to.userName == onlineUserModel.userName) {
message = concat("You", item.content, "...");
}
})
);
return message;
}
If you want to return the message as an Observable<string> you can do something like this:
getLastMessage(onlineUserModel: OnlineUserModel): Observable<string> {
return this.allDirectMessages$
.pipe(
filter((f) =>
f.messageModel.to.userName === onlineUserModel.userName ||
f.messageModel.from.userName === onlineUserModel.userName
),
map((data) => {
const item = data[data.length - 1].messageModel;
if (item.to.userName == onlineUserModel.userName) {
return `You ${item.content}...`;
}
else (item.from.userName == onlineUserModel.userName) {
return `Them ${item.content}...`;
}
})
);
}
I try to share you my result, just I added the map operator before filter:
getLastMessage(onlineUserModel: OnlineUserModel): Observable<string> {
return this.allDirectMessages$
.pipe(
filter((f) =>
f.messageModel.to.userName === onlineUserModel.userName ||
f.messageModel.from.userName === onlineUserModel.userName
),
map((data) => {
const item = data[data.length - 1].messageModel;
if (item.to.userName == onlineUserModel.userName) {
return `You ${item.content}...`;
}
else (item.from.userName == onlineUserModel.userName) {
return `Them ${item.content}...`;
}
})
);
}

Finding role by name when it has a space

My bot can issue roles by mention, but I want it to be given by name (so that there's no need to ping the entire role. This is the syntax of the command: !role <#user> <role name>
I'm using discord.js#v12
const Discord = require("discord.js");
module.exports.run = async(bot, message, args) => {
if (!message.member.roles.cache.has('706754890294099990')) return message.channel.send(`${message.author}, roles can only be assigned by admins`).then(msg => {
setTimeout(() => {
msg.delete()
}, 5000);
})
let rMember = message.mentions.members.first()
if (!rMember) return message.reply(`You didn't mention any user`).then(msg => {
setTimeout(() => {
msg.delete()
}, 5000);
})
let role = message.guild.roles.cache.find(role => role.name. == args[1]) || message.mentions.roles.first()
if (!role) return message.channel.send(`${message.author}, You haven't written any role name`).then(msg => {
setTimeout(() => {
msg.delete()
}, 5000);
})
if (rMember.roles.cache.has(role.id)) return message.reply(`This member already has this role!`).then(msg => {
setTimeout(() => {
msg.delete()
}, 5000);
})
if (rMember.roles.cache.has(role.id)) {
} else {
await (rMember.roles.add(role.id));
message.channel.send(`${message.author} Added __${role.name}__ to ${rMember}`);
}
}
module.exports.help = {
name: "role"
}
If your role has spaces in its name that means that your args will be something like this: ['#user', 'Name', 'in', 'parts']
To get the full name you need to join together all the arguments except for the first one, which is the user. To do that, you can use Array.slice() and Array.join(); here's an example:
let roleName = args
.slice(1) // Take every element from index 1 to the end
.join(' ') // Join them back with spaces
let role = message.guild.roles.cache.find(r => r.name == roleName) || message.mentions.roles.first()

How to make constraint different for id

In my ReactJS app I'm fetching information from my NodeJS app to display on the page the album by id. When I add songs to my database it has to go through the POST request and add the info to the database but the database has a constraint where the index key has to be unique. What I'm trying to do in the code below is use Promises to select album by id then insert the data on that album_id so that the insert and constraint is only ran on that id. This doesn't work and the constraint is still ran on all objects the same. Does anyone have a solution as on what I could do in order to run the constraint separately so that different albums can have the same index?
const addSong = (request, response) => {
const id = parseInt(request.params.id)
const { name, link, index, album_id } = request.body;
let p = new Promise((resolve, reject) => {
if(true) {
resolve('Success')
} else {
reject('Failed')
}
})
for (let i = 0; i < request.body.length; i++) {
const object = request.body[i]
p.then(() => {
pool.query('SELECT * FROM songs WHERE album_id = $1', [album_id], (error, results) => {
if (error) {
throw error
} else {
console.log("SELECT " + JSON.stringify(request.body));
}
})
})
.then(() => {
pool.query(
'INSERT INTO songs (name, link, index, album_id) VALUES ($1, $2, $3, $4) ON CONFLICT (index) DO NOTHING RETURNING *',
[
object.name,
object.link,
object.index,
object.album_id,
],
(error, results) => {
if (error != null) {
console.log(error)
} else {
console.log('INSERT ' + JSON.stringify(request.body))
}
}
)
})
.catch(err => {
console.log(err)
})
}
}

custom validation query always fires - express validator

I am trying to implement validation using express validator that should only kick in if the field actually has some input. If it is empty it should just be ignored. The first part of the validation if the field is to check to check it meets the regex requirements and the second check is to see if the value exists in the database. Lower case versions of the same username with capital letters are not allowed ie: Shirley and shirley are seen as the same thing.
body('username')
.trim()
.custom((value, { req }) => {
var regex = /^[a-zA-Z0-9]{5,20}$/;
if (value != '' && !value.match(regex)) {
throw new Error('Username does not meet required criteria.');
}
return true;
})
.custom((value, { req }) => {
if (value !== '') {
return User.findOne({ username: new RegExp(`^${value}$`, 'i') })
.then(userDoc => {
if (userDoc) {
return Promise.reject('Username unavailable');
}
return true;
});
}
}),
If I leave the username field empty I still get a validation error telling me 'username unavailable'
Managed to get it working like this
.custom(value => {
if (value !== '') {
return User.findOne({ username: new RegExp(`^${value}$`, 'i') })
.then(userDoc => {
if (userDoc) {
return Promise.reject('Username not available');
} else {
return true;
}
})
} else {
return true;
}
})

how to return an object form the mongodb resultant while in asyn calls

i am not getting the perfect result though i used promise in my project, some times the getSubCats function is returning the empty object and some times that function returning the resultant of subCategories
what i tried
exports.getCatsVthSubcats = function (req, res) {
var catsArray = [];
Category.find({active:true}).exec(function (err, cats) {
if (err) {
console.log("Error : " + JSON.stringify(err))
} else {
for (var i = 0; i < cats.length; i++) {
var catId = cats[i].catId;
catsArray.push(getSubCats(catId));
}
Promise.all(catsArray).then(results => {
console.log("REULT : " + JSON.stringify(results))
})
}
})
}
function getSubCats(catId) {
return SubCats.find({
catId: catId,
active: true
}).exec(function (err, subCategories) {
var obj = {
catId: catId,
subcats: subCategories
}
return obj;
})
}
what iam getting the result
console.log(catsArray )
[
[
{
category : "vegitarian",
rank : 23
},
{
category : "Non-vegitarian",
rank : 2
}
],
[], // some times getSubCats function returning empty array
[
{
category : "appetizers",
rank : 3
},
{
category : "nonveg-appitizers",
rank : 52
}
]
]
what i want
console.log(catsArray )
[
{ catId : Vegitarian,
subcat :[
{
category : "vegitarian",
rank : 23
},
{
category : "Non-vegitarian",
rank : 2
}
]
},
{ catId : "Non-vegetarian",
subcats :[
{
category : "appetizers",
rank : 3
},
{
category : "nonveg-appitizers",
rank : 52
}
]
}
]
thanks in advance
You're getting this result, because you're using Model.find (returns an array of objects), when you need to use Model.findOne (returns single element or null).
Besides of this your code could be simplified. You shouldn't mix callbacks style and promises:
exports.getCatsVthSubcats = (req, res) => {
Category
.find({ active: true })
.then(cats => {
let catIds = cats.map(cat => cat.catId);
return Promise.all(catIds);
})
.then(results => console.log("REULT : " + JSON.stringify(results)))
.catch(err => console.log("Error : " + JSON.stringify(err)));
}
function getSubCats(catId) {
return SubCats
.find({
catId: catId,
active: true
})
.then(subcats => {
var obj = {
catId: catId,
subcats
}
return obj;
});
}

Resources