简体   繁体   中英

Relationship condition if user is logged in

I want to create a relationship that checks if a user has liked a post. In order to do this, the relationship needs to check if the user is logged in, and then use their user_id to get the like record. Something like:

public function userLike() {
    if (Auth::check()) return $this->hasOne('App\Like')->where('user_id', Auth::user()->id);
}

However, this doesn't work. Additionally, if the user is not logged in and this relationship is called (which it is by default), it will return an error.

What is the proper way of doing this?

If you want to conditionally load a relation then you can do so by lazy eager loading. In your example you could define the relation as

public function userLike() {
    return $this->hasOne('App\Like', 'user_id');
}  

Then in your controller (or wherever else) you can do the check for if the user is question is currently logged in user or not

$loggedInUser = auth()->user(); 
if($loggedInUser){
    $loggedInUser->load('userLike');
}  

Then you can continue with whatever you want to do with the loggedInUser and the userLike .

Say you have multiple users at a point (in your code) and you want to load the likes for only the currently logged in user then you can

//$users is a collection of multiple users - assumed
foreach($users as $user){
    if($user->email === auth()->user()->email){
        $user->load('userLike');
    }
}  

Hope this helps

This is how I would do that:

1) “likes” table

I would first create a table to store all the “likes” with columns for a “ post_id ” and a “ user_id

2) create the relationships

User Model

public function likes()
{
    return $this->belongsToMany('App\Post', 'likes', 'user_id', 'post_id');
}

Post Model

public function likes()
{
    return $this->belongsToMany('App\User', 'likes');
}

3) Post Controller - the method

I would do the followings:

  • check if user is logged in, otherwise throw an error
  • make sure post exists, otherwise throw an error
  • create a new entry in like table with user_id and post_id

(you can also check if the user is logged in directly on your route using a middleware)

4) In the view

I would call the controller method using an ajax call.

Not sure if I forgot something, but hopefully that can help you a little bit.

If you need to “like” more things than only post, check the polymorphic relationships.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM