Problem with matching users they like each other in Laravel project

mrmar :

I have like functionality in my Laravel project where currently user can like another user and it would write in a database table (likes_users) correctly like this.

id  user_id  liked_user_id  is_mutual_like
1      1           5               0 

Now I want to write a query or something that when the user with id 5, in this case, likes back user with id 1, it would update 'is_mutual_like' column to 1 or true as it is the boolean column. I need help on how to do that. Any help is appreciated. Here is my code.

UserController.php

<?php

namespace App\Http\Controllers;

use App\City;
use App\User;
use App\LikesUser;
use App\UserProfile;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;

class UserController extends Controller
{
    public function showProfile($username, Request $request)
    {
        $userId = Auth::user()->id;
        $likedUserId = User::all()->random(1)->first()->id;
        $q = LikesUser::likes($userId, $likedUserId);

        return view('profile.show');
    }
}

LikesUser.php

<?php

namespace App;

use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;

class LikesUser extends Model
{
    protected $fillable = [
        'user_id',
        'liked_user_id',
        'is_mutual_like',
    ];

    public static function likes($userId, $likedUserId)
    {
        if ($userId === $likedUserId) {
            return NULL;
        }

        $existingRequest = static::likesCheck($userId, $likedUserId);
        if (!empty($existingRequest)) {
            return NULL;
        }

        return static::newLikes($userId, $likedUserId);
    }


    public static function likesCheck($userId, $likedUserId)
    {
        return LikesUser::where('user_id', '=', $userId)->where('liked_user_id', $likedUserId)->count();
    }


    public static function newLikes($userId, $likedUserId)
    {
        return DB::table('likes_users')->insertGetId([
            'user_id'    => $userId,
            'liked_user_id' => $likedUserId,
        ]);

    }
}

User.php

<?php

namespace App;

use Carbon\Carbon;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;
    /**
    * The attributes that are mass assignable.
    *
    * @var array
    */
    protected $fillable = [
        'gender_id', 
        'city_id',
        'username', 
        'email', 
        'first_name',
        'last_name',
        'age',
        'date_of_birth',
        'premium',
        'active',
        'interested_in',
        'job',
        'mobile_number',
        'mobile_verification_id',
        'inform_new_message',
        'inform_gift_received',
        'inform_new_singles',
        'inform_whatchlist',
        'inform_when_liked',
        'inform_when_matched',

    ];

    protected $dates = [
        'date_of_birth',
        'email_verified_at',
        'mobile_verified_at',
        'premium_purchased_at',
    ];

    /**
    * The attributes that should be hidden for arrays.
    *
    * @var array
    */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
    * The attributes that should be cast to native types.
    *
    * @var array
    */
    protected $casts = [
        'premium' => 'boolean',
        'inform_new_message',
        'inform_gift_received',
        'inform_new_singles',
        'inform_whatchlist',
        'inform_when_liked',
        'inform_when_matched',
    ];

    /**
    * To get the users liked by the current user
    */
    public function likedUsers()
    {
        return $this->belongsToMany(User::class, 'likes_users', 'user_id', 'liked_user_id');
    }

    /**
    * To get the users who liked the current user
    */
    public function usersLiked()
    {
        return $this->belongsToMany(User::class, 'likes_users', 'liked_user_id', 'user_id');
    }

    public function mutualFriends()
    {
        return $this->belongsToMany(User::class, 'likes_users', 'liked_user_id', 'user_id')->where('likes_users.is_mutual_like', true);
    }

}

likes_users_table

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateLikesUsersTable extends Migration
{
    /**
    * Run the migrations.
    *
    * @return void
    */
    public function up()
    {
        Schema::create('likes_users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('user_id')->nullable();
            $table->unsignedBigInteger('liked_user_id')->nullable();
            $table->boolean('is_mutual_like')->default(false);
            $table->timestamps();
        });
    }

    /**
    * Reverse the migrations.
    *
    * @return void
    */
    public function down()
    {
        Schema::dropIfExists('likes_users');
    }
}
Ruben Danielyan :

I've edited my answer to match your method and variables

public static function newLikes($userId, $likedUserId)
{   
    // $userId is user1 next
    // $likedUserId is user2 next

    // check if the user2 already liked user1
    $mutual_like = LikesUser::where('liked_user_id', $userId)->where('user_id', $likedUserId)->first();

    // save user1 like
    $like = new LikesUser();
    $like->user_id = $userId;
    $like->liked_user_id = $likedUserId;
    $like->is_mutual_like = !!$mutual_like; // same as $mutual_like ? 1 : 0;
    $like->save();

    // also set is_mutual true for user2
    if($mutual_like){
        $mutual_like->is_mutual_like = 1;
        $mutual_like->save();
    }

    return "Anything you want to return";


}

Check if it works simply visiting a test route and run a function in it.

// web.php
Route::get('/test', function(){
    \App\LikesUser::newLikes(1,2);
    \App\LikesUser::newLikes(2,1);
});

And check your db, or just play with test route

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=11931&siteId=1