AlbraaHabibullah's avatar

follower can't follow himself

I want the user cant follow himself and this my migration

public function up(): void { Schema::disableForeignKeyConstraints(); Schema::create('follow_systems', function (Blueprint $table) { $table->uuid('id')->primary(); $table->uuid('follower_id'); $table->uuid('following_id'); $table->foreign('follower_id')->references('id')->on('users'); $table->foreign('following_id')->references('id')->on('users'); $table->date('followed_at')->default(now()); $table->unique(['follower_id', 'following_id']); $table->timestamps(); }); Schema::enableForeignKeyConstraints(); }

0 likes
3 replies
LaryAI's avatar
Level 58

To prevent a user from following themselves, you can add a check in your code before creating a new follow_system record. Here's an example of how you can do it:

// Assuming you have a FollowSystem model

public function store(Request $request)
{
    $followerId = $request->input('follower_id');
    $followingId = $request->input('following_id');

    // Check if the follower and following IDs are the same
    if ($followerId === $followingId) {
        return response()->json(['error' => 'You cannot follow yourself'], 400);
    }

    // Create the follow_system record
    $followSystem = new FollowSystem;
    $followSystem->follower_id = $followerId;
    $followSystem->following_id = $followingId;
    $followSystem->followed_at = now();
    $followSystem->save();

    return response()->json(['message' => 'Followed successfully'], 200);
}

In this example, we first check if the follower_id and following_id are the same. If they are, we return an error response indicating that the user cannot follow themselves. Otherwise, we proceed with creating the follow_system record as usual.

Note: This is just an example implementation. You may need to modify it based on your specific application structure and requirements.

Snapey's avatar
Snapey
Best Answer
Level 122

put a simple check in your code

You cant do it in the migration if that was your suggestion

1 like
jaseofspades88's avatar

Please wrap your code in backticks, the last thing any of us need to spend time doing in a day is trying to read illegible copy and paste.

@snapey is right, you cannot do this in the migration. Do it in code..

    if ($user->isNot(auth()->user())) {
        $user->befriend(auth()->user());
	}

Obviously this is simply pseudocode... you have to fill in the blanks

1 like

Please or to participate in this conversation.