In need of a logic to create comments in laravel - laravel

Ok so the basis is that I want to be able to have comments on each of my post. The comments will have a reply button for each. It’s not multi threaded so one comment will have many replies. Those replies won’t have replies. Also I want to be able to like and dislike a comment/reply. All of this will not be bind to the user model or any of such. The public visitors will be able to add comments and reply to comments but the approval is needed.
So here is the logic I got so far. Am I on the right track here (hoping this post may help someone else as well):
So i create aComment model. And then create a table named comments.
And I create a model named Reply and a table named replies
And finally, a model name Like and it’s table likes
So the relationship is:
comments will have many replies and replies belongs to one comment
replies & comments will have many likes.
And now for the logic:
I will use AJAX to call the store function on the CommentController to store comments. And I will call the store function on the ReplyController to store the replies. As for the likes, LikeController store function will store the likes for the comment and reply.
Here is the table structure:
Comments table
id
post_id
name
email
comment
approved
timestap
Replies table
id
comment_id
name
email
comment (or reply)
approved
timestamp
Likes table
id
comment_id
reply_id
like
dislike
timestamp
Now what I do not understand is, likes table. Is it right to have comment_id and reply_id and also like and dislike?
I could call the store function everytime someone clicks the like or dislike and have it stored in the table and update the column if it is a reply or a comment by it’s id to the respective id columns. Is the logic right?
Also, if you guys have any suggestions or better and efficient way of doing this, please let me know.
This is getting too long so I’ll just leave it here.
Edit
Also forgot to mention that I am not sure how I will be taking the amount of likes from db to blade and count it. Not with the current structure mentioned above. Also, how to check and see if the person already liked. And if so, don’t let them like again or dislike again. A liked person can not dislike. They can do only one thing.

I would definitely recommend associating comments, replied and likes to a User which you are pretty much already doing with comments and replies.
There are ways that you could have a "liking" system that would allow guest usage, however, this would be very easy to get around and ultimately make your "like" stats useless.
An example DB structure going forward would be:
comments and replies
id
post_id // or comment_id if on the replies table
user_id
body
approved
( "_at" dates)
likes
id
likeable_id // id of the comment or reply
likeable_type // Comment or Reply
user_id
liked (boolean)
("_at" dates)
The likes table is setup to be used as a Polymorphic relationship e.g. in your Comment model:
public function likes()
{
return $this->morphMany(Like::class, 'likeable');
}
Then to add a like you would have something like:
$like = new Like(['user_id' => auth()->user()->id, 'liked' => true]);
$comment->likes()->save();
There are many different ways you would then check if the current auth user has liked a post, one example would be to have a separate relationship so that you can eager load the results:
public function authUserLike()
{
return $this->morphOne(Like::class, 'likeable')->where('user_id', auth()->id());
}
Then if the auth_user_like is null they haven't already liked that comment.

I don't see any need of the Replies Table just use parent_id in comments table. This tutorial might help you get started Nesting Comments in Laravel

Related

Laravel many-to-many

I've Googled for a while and found multiple threads discussing problems like this, but I just can't get my head around how to do exactly what I want to do, hope someone can point me in the correct direction.
I'm making a learning platform in Laravel. What I want right now is that when lesson A is completed by someone belonging to workplace B a notification should be sent to user C. So I have made a table notification_receivers containing lesson_id, workplace_id, and user_id, pointing to the respective tables.
Of course, I also have the corresponding models (User, Lesson, Workplace) set up, but what I can't understand is exactly how to set up the model relations. I'm currently making the Blade template used for editing the notification receivers belonging to a particular lesson, and I need to make the following: Get all notification receiver users for this lesson and then for every one of those users, get the related workplaces.
My first try was this in the Lesson model:
public function notification_receivers(): BelongsToMany
{
return $this->belongsToMany('App\User', 'notification_receivers')->withPivot(["workplace_id"]);
}
Which of course doesn't work straight off, since some users will be returned multiple times (once for each workplace). How do I do to get every user just once?
And when I have my users, how do I get the workplaces for each user? If I get it to work, the withPivot above will give me the IDs, but how do I get a collection of the Workplaces?

Parse js sdk, How do you query many to many in document DB?

In the Parse js guide it says:
For example, a User may have many Posts that she might like. In this case, you can store the set of Posts that a User likes using relation. In order to add a Post to the “likes” list of the User, you can do:
var user = Parse.User.current();
var relation = user.relation("likes");
relation.add(post);
user.save();
My use case is actually this exact setup. We have Users and they can "like" 0-many Posts, so I set it up exactly as stated above. My issue now is that for a given Post or set of Posts, I need to query how many users have liked each Post. I'm having trouble figuring out how to query for that... Can someone help me out? I'm not sure if this is a limitation or if I just don't know enough to figure this out. I've thought about storing a counter on the Post itself and using increment() and decrement() each time a User likes or unlikes a Post, but I'd rather not if I can get away with it.
There are a couple of ways you can do this. One would be to also have a relation on each post for likedBy so when a user likes a post, you add that user to the post's likedBy relation as well as adding the post the user's likes relation.
Another solution is to create a new Parse class for Like. Whenever a User likes a post, you create a new Like with a pointer to the Post and the User who liked it. Then if you want to find the posts that a user likes, you can easily query that, or if you want to know which users like a post, that query is just as simple.
I personally use the second approach, but either will work

How to list related blog posts in OctoberCMS

I am building an App with OctoberCMS and wanted to list related blog posts at the bottom of each post page basing on categories. I figured out rainlab_blog_posts table does not have a foreign key pointing to blog categories table. To achieve what wanted I thought of extending the blog_posts table and added category_id as foreign key using a plugin. I defined foreign key constraints in table migration. Everthing seem to be fine. My challenge is, How can I insert category id in posts table each time a new post is created. OctoberCMS create post backend has an option where the author assigns a category to a new blog post by selecting from list. Just don't understand how to pass this category id and insert into rainlab_blog_posts table in category_id field.
This is what I want to achieve in my API:
routes.php
use Rainlab\Blog\Models\Post;
Route::get('apiv1/related-posts/{postid}',function($id)
{
$post = Post::where('id',$id)->first();
$posts = Post::where('category_id',$post->category_id)
->where('id','!=',$id)
->orderBy('views','desc')
->get()->take(5);
return $posts;
});
Or if there is a better way of achieving this will appreciate. Cheers!
Hmm seems something wrong here,
As first I can see from Blog Plugin that Blog <=> Category it is MM relation so you will not find category_id in rainlab_blog_posts table as all relation is maintained by this mm-relation table rainlab_blog_posts_categories.
So I think you will select only one category for blog so you can get related blogs for only that category. [ assuming from your code and description ]
we can utilize relationships for that.
So your code can look like this
use Rainlab\Blog\Models\Post;
Route::get('apiv1/related-posts/{postid}', function($id)
{
$post = Post::where('id',$id)->first();
// we need this because there will be mm relation so
// we fetch first category and this will be based on
// [ name sorting - does not matter as there will be only one cat. ]
$firstCategory = $post->categories()->first();
// now we fetch only that post which are related to that category
// but we skip current post and sort them and pick 5 posts
$posts = $firstCategory->posts()
->where('id', '!=', $id)
->orderBy('views','desc')
->limit(5) // use limit instead of take()
->get();
// use limit instead of take() as we don't need extra data so
// just put limit in sql rather fetching it from db then
// putting limit by code - limit() is more optimised way
return $posts;
});
Good thing now you don't need to add that category_id field on rainlab_blog_posts. So, I guess now you Also don't need to worry about adding it during post insertion.
if any doubts please comment.
Incase you simply want to display related blog posts without having to customize the blog database, there is an OctoberCMS plugin called Related Articles
that requires rainlab blog plugin. It will display all the other articles belonging to the post's category.
On your Backend menu, go to settings,on System, go to Updates and Plugins.
Go to Install plugins. Search for plugin Related articles. The creator is Tallpro. Install it.
Go to CMS. On the page you want related articles, go to components and drag Related articles. Save and preview it. You can also fork the component to edit how you want your related articles to be displayed. You will find more information on the documentation.
If you encounter any problems feel free to inquire or you can check out the plugin reviews for problems faced and their solution.

Laravel 5.2 eloquent model order by their relation model attribute

I have a question. I have an user model and a post model. A user can have many posts. Now I need to get posts with pagination. And I need to sort posts by their related user's id desc. Per page number is 10. I do not know how to write this code, someone can help me? Thanks.
Since Post belongs to User the posts table has user_id key. Use it:
Post::orderBy('user_id', 'desc')->paginate(10);

How to join two belongsToMany objects

I am trying to represent friendships in my Laravel project database.
I have created a table profile which contains all user-data.
A second table profile_profile with the columns profile_id and friend_id.
With that I am able to get persons wo wants to be friend with me:
$this->belongsToMany('App\Profile', 'profile_profile', 'friend_id', 'friend_id');
an friends I am want to be befriendet:
$this->belongsToMany('App\Profile', 'profile_profile', 'profile_id', 'friend_id');
But in the end you are only friends if both want that so. So I tried to combined them but join or something similar didn't work.
I did a research on this platform and google over 2 hours. I am afraid that my skills are to limited, but I really like to ask for help.
Thank you in advance.
Quick solution: add another column in the profile_profile table, say, "accepted" as boolean and default to FALSE.
When a user accepts a friend's request, toggle the "accepted" field to TRUE.
Then you could search like $profile->profiles()->wherePivot('accepted', true)->get()

Resources