I'm working on reactJs with laravel CHAT. I want to display juste the last message from the sender. But I usually get all his messages. I tried lot of attempts But I didn't get the solution yet. this is my last attempt:
$types= chat::select('id','senderId')->where('userId', $id)->get();
foreach ($types as $chats) {
$chats->chat = chat::select('id','unseenMsgs', 'senderId')->where('senderId', $chats->senderId)
->get();
foreach ($chats->chat as $child){
$child->lastMessage = chat::select('userId','message', 'time', 'senderId')
->where('id', $child->id)
->orderBy('id', 'asc')->skip(0)->take(1)
->get();
}
}
return ['chatsContacts' => $types];
The userId is the receiver one and senderId is the one who send the message. At first query I tried to get all the messages that are sent to the reciever. The question is how to ignore the duplication and get juste the last message from the sender one. and Thanks in advance for your help
Ps: I'm using An MVP and the reponse should be like this:
this picture is for the response in the MVP
That's why in my server side I should create an api which return exactly this response
It is hard to recreate the issue with the amount of information provided.
From what I understand about the problem description, following seems like a possible solution:
$latestChats = chat::select('id', 'userId', 'message', 'time', 'senderId')
->where('userId', $id)
->orderBy('id', 'desc')
->get()
->unique('senderId');
return ['chatsContacts' => $latestChats];
This should give you a collection containing the last messages sent by every senderId to the specified userId.
If this does not resolve your issue please provide further information.
What does the table look like?
What is the exact format you're looking for in chatContacts ?
Related
In the documentation, it states that a Message can have an array of Embeds.
This obviously makes one question if it's possible to send multiple RichEmbed with a single message.
The normal way to send an Embed is to use a MessageOptions Object, like this:
message.channel.send({embed: embedName});
Although this doesn't seem to allow for a multiple of RichEmbeds, does anyone know if it's possible to send multiple?
As Abz6is pointed out, you can post multiple RichEmbeds at once by using a Webhook.
Here is the documentation for the WebhookMessageOptions.
Quick example:
message.channel.createWebhook('Webhook Name', message.author.displayAvatarURL)
.then(w => w.send({embeds: [
new Discord.RichEmbed().setAuthor('Embed 1'),
new Discord.RichEmbed().setAuthor('Embed 2'),
]}));
This works for up to 10 embeds.
Yes! it is Possible to do this, by doing
if(message.content.startswith(Anything)) {
message.channel.send({embed: embedName});
message.channel.send({embed: embedName});
}
Caltrop's Answer also Works.
I'm working in a MongoDB query with Nodejs and I have a problem that I can't resolve.
Let us supposed we have a lot of documents in Mongo and each document have a tags array
tags: [tag1, tag2, tag3]
Front-end are going to send the parameters and we want to make a query with those... How can I find every document inside Mongo with those tags. The tags can be differents, not all documents have the same tags but I want to pull each document that have almost one of those tags. I don't know if I make myself clear with this but I hope you'll help me.
PD: If the query works, we have more than 13 that I can apply so it needs to be something like dynamically query o something.
Regards
This is where the mongodb's aggregate function comes in play
lets say there is a database called books and we want to get books that contain lets say ['fantasy', 'sci-fi'] in its genres
db.book.aggregate([{
$match:{
genres:{
$in:['fantasy', 'sci-fi']
}
}
}])
this will get the result you want, finding all the books that contain either fantasy, or scifi
db.book.aggregate([{
$match:{
genres:{
$all:['fantasy', 'sci-fi']
}
}
}])
This will get all the books that have genres with both fantasy and sf
db.book.aggregate([{
$match:{
genres:{
$nin:['fantasy', 'sci-fi']
}
}
}])
This will fetch all the books that don't have these values
generate an $or condition in your code according to the parameters:
let or_array = [];
params.forEach(params, (tag_param) => {
or_array.push({tags: tag_param})
});
let or_cond = {$or: or_array};
now we just need a simple find query to retrieve the documents:
let results = model.find(or_cond);
results should contain the wanted documents.
** note that $or requires a none empty array so you should validate at least one parameter is received from the client side.
I need to get the name of each like on each post on a group page. Since I first have to get some data from the original post, I'm trying to make a connection then iterate through the likes and get a list of the users who liked each post. Here's what I have:
Connection<Likes> feedLikes = postFeed.fetchConnection(id+"/likes", Likes.class, Parameter.with("fields","from,actions,type"));
// Get the iterator
Iterator<List<Likes>> likeIt = feedLikes.iterator();
while(likeIt.hasNext()) {
List<Likes> likeFeed = likeIt.next();
for (Likes currLike: likeFeed) {
String ObjectId = id;
String LikeUserId = currLike.getId();
String LikeUserName = currLike.getName();
like_data.add(new String[] {ObjectId, LikeUserId, LikeUserName});
}
}
This doesn't work and I'm a little stuck on why. I know the username is stored in Likes.LikeItem but I can't even get to that step so far. Does anyone have any idea what I'm missing?
According to the Facebook reference this is not possible (https://developers.facebook.com/docs/graph-api/reference/v3.2/object/likes):
A User or Page can only query their own likes. Other Users'or Pages' likes are unavailable due to privacy concerns.
Only aggregated counts using total_count with the summary parameter are available for Post likes.
I have read and worked with the other posts about this and it appears the version of Laravel 4 I just downloaded has more changes made to the way the JSON input is handled by a controller.
$input = Input::json()->all(); gives me errors as if I am referring to something that does not exist when I request some part of the payload after doing a PUT request. And without ->all(); I get a symfony error.
Does anyone know how to get good JSON from backbone in Laravel 4's latest version?
Currently, I am doing the long way around to get my data, ie:
$input_title = Input::get('title');
$input_completed = Input::get('completed');
$task = Task::find($id);
$task->title = $input_title;
$task->completed = $input_completed;
$task->save();
Yes, I am doing the tutorial on tutsplus to learn laravel/backbone, so a little noob patience is apreciated.
The error I get when using Input::get(); is:
{"error":{"type":"UnexpectedValueException","message":"The Response content must be a string or object implementing __toString(), \"array\" given.","file":"/Users/brentlawson23/Sites/laravel4App/bootstrap/compiled.php","line":16858}}
I really want to get the Laravel-specific answer instead of using straight php to stringify the payload.
I get same error using just Input::json();
For the current beta of Laravel 4, Input::json(); is not getting a stringified version of the request payload that can be used to create a new row in a table, nor does Input::json()->all(); (hoping to play nice with the ParameterBag from symfony). I have tried json_encode among other hacks and basically every step of the way in this tut, I hit some brick wall. Anyone have a suggestion based on what I have presented here?
Today I got this when simply trying to echo the result of $input = Input::json(); :
{"error":{"type":"ErrorException","message":"Catchable Fatal Error: Object of class Symfony\Component\HttpFoundation\ParameterBag could not be converted to string in /Users/brentlawson23/Sites/laravel4App/app/controllers/TasksController.php line 45","file":"/Users/brentlawson23/Sites/laravel4App/app/controllers/TasksController.php","line":45}}
Yes, I have studied the Symfony API.
I had a similar problem. Input from Backbone is converted to array in Laravel. On tutsplus, Jeffrey Way is using object. So I was trying to do this (like in tutorial):
return $input->title // using object,but got an error.
If I change that line to:
return $input["title"] // everything works fine with array.
I'm also working through the Backbone tutorial on tuts+. If I'm right in assuming are you stuck on the Creating New Contacts section? Below is how I got it to work for me, in ContactController.php:
public function store()
{
$input = Input::all();
Contact::create(array(
'first_name' => $input['first_name'],
'last_name' => $input['last_name'],
'email_address' => $input['email_address'],
'description' => $input['description']
));
}
And then also needed to update app/models/Contact.php with the below:
class Contact extends Eloquent {
protected $fillable = array('first_name', 'last_name', 'email_address', 'description');
}
That should get it working for you and insert the contact into the database. If I've misread let me know and I can have another look.
Cheers,
Sean
I have been trying out backbone.js and have been stymied when I create a new model object then call model.save(). I am expecting the backbone.js default behavior to update the model object with the id from the database but it is not. Is this not supposed to happen? I have verified that I am getting a post with the attributes in json format. My server saves the json to a table and then returns the json with a new id field to backbone.js. Is this correct? Should my server return the entire new object or just the id or what?
//contents of the POST from backbone.js
{ "text":"this is a test" }
//reply from my server
{ id:"15", text:"this is a test" }
My sample code is below
var SQLRow = Backbone.Model.extend({
table:"",
urlRoot:'db',
url:function () {
return "/" + this.urlRoot + "?table=" + this.table +
"&id=" + this.attributes.id;
}
});
var Xtra = SQLRow.extend ({
table:'Xtra'
});
var row = new Xtra({
text: "this is a test"
});
alert(row.url());
row.save()
alert("row:" + row.get("id"));
Tough to tell from your post. Two ideas :
1) the response from the server isn't successful What does your save call return ?
2) Your "id" attribute is named something other than ID. To account for the different name add the following to your model :
idAttribute : "MyModelsID",
EDIT
You're likely facing a timing issue, where the alert fires before the ID has returned. Instead of your last two lines try this :
row.save( null,
{
success : function(model, response) { alert(model.get('id'); }
}
);
ALTERNATIVE
As #mu_is_too_short mentioned, another way is to listen for the change even on the model and respond to the event. (i was just trying to keep the answer as close to your code as possible). But something like the following pseudo code should get you started...
var myView = Backbone.View.extend({
....
initialize : function () {
this.collection.bind('change', this.SOME_LISTENING_FUNC );
}
});
OR, if you're in a collection/view-less world something like this creates a listenr ...
row.on('change', function() { /* do stuff */ }, this);
This answer is based on one comment of Cjolly in the answer above.
It is essential for making the Backbone.Model.save([attributes],[options]) successful in assiging the model with the newly generated model's id from the server, that the server returns the model's id in a JSON string like this { "id" : <the id> }. (note it is "id" and not id).
In essence backbone rightly expects a JSON string and in contrast to how objects may be defined in Javascript without quoted keys, JSON requires the object keys to be quoted (see JSON Spec - does the key have to be surrounded with quotes?)
Since according to Cjolly's comment this has been the essential problem, I want to hightlight this solution in an second answer. Partially because I was hit by the very same problem and only by reading througth the comments I was able to receive the insight.
I've faced the same issue and what I've found is that my validate function of the saved model actually invalidates the model returned from the back end. That's why my fields were not updated properly.
Maybe its a little outtimed, but today I had the same missing id.
It turns out, that the server just sends a Header 'Location' with a redirect containing the new id, but dosen't return the persisted object.
Adding the object to the response was the solution.
It seems, that not returning the object is standard behavier with Roo(Spring) generated Json-Controllers.