I have posts, users and favorites table.
For example, I make some post favorited for a user with an id of 3 like this :
User::find(3)->favorites()->attach($post->id);
and if users send request twice it will insert this favorite with this post_id, user_id twice.
I want to check if a post is not liked by this user, then save record in the database.
or if a post is favorited then unfavorite it.
how can I do this with eloquent relationship ??
I have User, Post models.
You could use toggle():
User::find(3)->favorites()->toggle($post->id);
This would like it if it not liked, and unlike it if it is.
If you just want the function not to duplicate likes in the table, just use syncWithoutDetaching:
User::find(3)->favorites()->syncWithoutDetaching([$post->id]);
Putting this on your User model:
class User extends Model {
public function like($postId){
$this->favorites()->syncWithoutDetaching([$post->id]);
}
public function unlike($postId){
$this->favorites()->detach([$post->id]);
}
}
Related
I'm working on a small project using Laravel, and I would like to create a like and dislike system, so a user can like one to many more users.
I already have a table called Users (default by Laravel), now I have created another table called favorite_user with id, user_id and liked_the_user.
How can I get all the users that a user already liked? Is my table correct or should I change something?
All what I want to do is add like and show the people I liked. I don't know how to make this relationship since I am new to Laravel.
Thank you
Looks like you have a pivot table there so a Many to Many relationship is what you need to setup. You will need to pass some additional arguments since the naming won't fit with convention.
User Model:
// users the user has liked
public function liked()
{
return $this->belongsToMany(self::class, 'favorite_user', 'user_id', 'liked_the_user');
}
// users who like the user
public function likes()
{
return $this->belongsToMany(self::class, 'favorite_user', 'liked_the_user', 'user_id');
}
Controller:
public function liked(Request $request)
{
// get liked users for current user
$liked = $request->user()->liked;
// get liked users for an arbitrary user
$liked = User::findOrFail(...)->liked;
...
}
Laravel 8.x Docs - Eloquent - Relationships - Many to Many - belongsToMany
i have a rating table.
The model relationship:
Rating is belongs to user & User has many rating.
The scenario is users have a profile page. It will display all ratings and users information who rate for the particular user.
I using $ratings= Rating::where('user_id',$user->id)->get();
But this only return rating information which belong to the user. No rater information.
How can i get rater information by rater_id?
if you want to build relationship in your model then you can
public function rater() {
return $this->belongsTo(User::class, 'rater_id');
}
now you can get the rater
$ratings= Rating::with('rater')->where('user_id',$user->id)->get();
Trying to figure what table I need to make this relationship to work...
I'd like the user to mark a post as favorite and save it so when he log back in, he can view all his favorite posts.
So I have User and Post models and their relationships of course.
User hasMany Post, Post belongTo User
Do I need to add Favorite model and add fav_id to both User and Post models ?
Or maybe adding pivot table?
If a favorite is defined as a simple relationship between users and posts, you don't need a model for it. However, you do want a pivot table, call it something like favorites. It would contain id, post_id, user_id, created_at, updated_at.
Then in your user model:
public function favoritePosts()
{
return $this->belongsToMany('Post', 'favorites');
}
And in the post model:
public function favoritedBy()
{
return $this->belongsToMany('User', 'favorites');
}
So now, for any given user, you can do $user->favoritePosts to get an array of posts that user has "favorited".
And from a post object, you can do $post->favoritedBy, to get an array of users that have favorited that post.
I haven't tested this but that seems like that would work off the top of my head.
how can I pull all the posts of a certain user? should i foreach all the posts of a certain user? Like if user1 posted something and I want to pull out whatever he posted and only shows when he's logged in.
In Laravel, if you are using Eloquent relationships things would look something like this.
First, define your relationships within your models. If you're following the example below, I'm going to assume the following.
Your users table in database is named users. Your posts table in
database is named posts, and has an integer column named user_id
corresponding to the id of the user the post belongs to. If your
table and column names are different, make sure you read the Laravel
docs to learn how to set custom table names and column names for
Eloquent models.
app/models/User.php
<?php
class User extends Eloquent {
// All the default User.php stuff....
public function posts()
{
return $this->hasMany('Post');
}
}
app/models/Post.php
class Post extends Eloquent {
public function user()
{
return $this->belongsTo('User');
}
}
After we've defined those relationships, you can get a particular user using something like this.
$user = User::find(1); // This will get the user with an ID of one.
Then, you retrieve that user's posts, we can use the Eloquent relationship we defined earlier.
$posts = $user->posts()->all();
If the user is already logged in, you can user the Auth class to do this for the logged in user.
$posts = Auth::user()->posts()->all();
You'll now realize that ->posts() actually returns a Collection, and you can use all of the Query and Eloquent methods on that collection as normal.
I got three tables called threads,posts,users
threads got
id
title
etc.
posts got
id
thread_id
user_id
post
post_date
etc.
users got
id
username
password
email
etc.
when users wants to view a thread i simply call a jquery ajax request using post data to send thread id and return this code :
Response::eloquent(Thread::find(Input::get('threadid'))->posts()->get());
this code does his job perfectly and return posts by same thread_id. (post model also eager loads the user by looking user_id).
however this code grabs every attribute of posts and users i mean everything to json, post_date, post_updatereason, user_password, user_email all columns in tables.
I just want to grab post, username and post_date with json
You can add public static $hidden = array('list', 'of', 'fields'); to your model which extends Eloquent. Then none of the fields which you enumarate in the array will be returned. For more information refer to the documentation.
For example
class User extends Eloquent {
public static $hidden = array('password', 'email');
}
will return the user model without the password and email.
If you are using laravel 3, and this is probably the same for version 4, you should be able to specific the columns you want using the get method.
Response::eloquent(Thread::find(Input::get('threadid'))->posts()->get(['username','post_date']));