Laravel: matches array (Tinder clone) to my user returns empty

  laravel, php

I’m making a Tinder clone to practice, I want to retrieve a user matches (when both users like eachother) but when I do:

$user = User::with('matches')->findOrFail(1);

The matches array returns empty, despite all users liking eachothers,

I created a Users_Users_liked pivot table:

Schema::create('users_users_liked', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user_id')->index();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
            $table->unsignedInteger('user_liked_id')->nullable()->index();
            $table->foreign('user_liked_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
            $table->timestamps();
        });

I set up the User model with relationship as follows (notice matches realtionship, which always returns an empty array)

public function likesToUsers()
    {
        return $this->belongsToMany(self::class, 'Users_Users_liked', 'user_id', 'user_liked_id');
    }

    public function likesFromUsers()
    {
        return $this->belongsToMany(self::class, 'Users_Users_liked', 'user_liked_id', 'user_id');
    }

    public function matches()
    {
        return $this->likesFromUsers()->whereIn('user_id', $this->likesToUsers->keyBy('id'));
    }

In my UsersSeeder I give likes to user 1 from all users

        $users = json_decode($json, true);

        foreach ($users as $data)
        {
            $user = new User();
            $user->name = $data['name'];
            $user->save();

            if($user->id > 1)
            {
                $user->likesToUsers()->attach([1]);
                $user->save();
            }

        }

        $user = User::findOrFail(1);
        $user->likesToUsers()->attach([2,3,4,5,6,7,8,9,10,11]);
        $user->save();

Source: Laravel

Leave a Reply