Home > OS >  How to show the status of friendship in relation to an authorized user in laravel?
How to show the status of friendship in relation to an authorized user in laravel?

Time:01-02

I am learning react native and using laravel as backend. How to write an action in a laravel to display a list of users (for searching by users on the frontend) to show status everyone's friendship is for an authorized user "Pending", "Confirmed", "Blocked" to respectively show the desired button for example "Add friend", "Accept friend request", "Remove from friends" and "Block"? My code:

Friendship table migration:

Schema::create('friendships', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('first_user')->index();
        $table->unsignedBigInteger('second_user')->index();
        $table->unsignedBigInteger('acted_user')->index();
        $table->enum('status', ['pending', 'confirmed', 'blocked']);
        $table->timestamps();
});

User model:

//======================== functions to get friends attribute =========================

    // friendship that this user started
    protected function friendsOfThisUser()
    {
        return $this->belongsToMany(User::class, 'friendships', 'first_user', 'second_user')
                    ->withPivot('status')
                    ->wherePivot('status', 'confirmed');
    }

    // friendship that this user was asked for
    protected function thisUserFriendOf()
    {
        return $this->belongsToMany(User::class, 'friendships', 'second_user', 'first_user')
                    ->withPivot('status')
                    ->wherePivot('status', 'confirmed');
    }

    // accessor allowing you call $user->friends
    public function getFriendsAttribute()
    {
        if ( ! array_key_exists('friends', $this->relations)) $this->loadFriends();
        return $this->getRelation('friends');
    }

    protected function loadFriends()
    {
        if ( ! array_key_exists('friends', $this->relations)) {
            $friends = $this->mergeFriends();
            $this->setRelation('friends', $friends);
        }
    }

    protected function mergeFriends()
    {
        if($temp = $this->friendsOfThisUser) {
            return $temp->merge($this->thisUserFriendOf);
        } else {
            return $this->thisUserFriendOf;
        }
    }
    //======================== end functions to get friends attribute =========================

    //====================== functions to get blocked_friends attribute ============================

    // friendship that this user started but now blocked
    protected function friendsOfThisUserBlocked()
    {
        return $this->belongsToMany(User::class, 'friendships', 'first_user', 'second_user')
                    ->withPivot('status', 'acted_user')
                    ->wherePivot('status', 'blocked')
                    ->wherePivot('acted_user', 'first_user');
    }

    // friendship that this user was asked for but now blocked
    protected function thisUserFriendOfBlocked()
    {
        return $this->belongsToMany(User::class, 'friendships', 'second_user', 'first_user')
                    ->withPivot('status', 'acted_user')
                    ->wherePivot('status', 'blocked')
                    ->wherePivot('acted_user', 'second_user');
    }

    // accessor allowing you call $user->blocked_friends
    public function getBlockedFriendsAttribute()
    {
        if ( ! array_key_exists('blocked_friends', $this->relations)) $this->loadBlockedFriends();
            return $this->getRelation('blocked_friends');
    }

    protected function loadBlockedFriends()
    {
        if ( ! array_key_exists('blocked_friends', $this->relations)) {
            $friends = $this->mergeBlockedFriends();
            $this->setRelation('blocked_friends', $friends);
        }
    }

    protected function mergeBlockedFriends()
    {
        if($temp = $this->friendsOfThisUserBlocked) {
            return $temp->merge($this->thisUserFriendOfBlocked);
        } else {
            return $this->thisUserFriendOfBlocked;
        }
    }
    // ======================================= end functions to get block_friends attribute =========

    public function friend_requests()
    {
        return $this->hasMany(Friendship::class, 'second_user')
                    ->where('status', 'pending');
    }

Function in controller:

public function show(Request $request)
    {
        $user = auth()->user();
        $users = User::where('id', '!=', $user->id)->get();

        return UserInfoResource::collection($users);
    }

I tried to do something like this in the resource:

public function toArray($request)
    {
        return [
            "id"                => $this->id,
            "uuid"              => $this->uuid,
            "first_name"        => $this->first_name,
            "last_name"         => $this->last_name,
            "avatar"            => asset( 'storage/' . $this->avatar ),

            "friendship"        => $this->friends->only([auth()->user()->id])->first(),
            // "friendship"        => $this->pivot,
        ];
    }

But ->friends only shows "confirmed" friendships, how can I track the rest of the statuses?

CodePudding user response:

Since you have set:

->wherePivot('status', 'confirmed');

you will only get the friends with that specific status.

There is a wherePivotIn()-method that allows you to add multiple values to match for.

Changing it to something like:

->wherePivotIn('status', ['confirmed', 'anotherStatus', ...etc...]);

should give you the friends with the other statuses as well.

You can read more in the manual about that method (and others)

  • Related