@saneesh you're attaching the user to followings, but dumping followers.
Auth::user()->following()->attach($userJohn); should be $userJohn->following()->attach(Auth::user());
Hi All, I'm following Adam Wathan's 'Test Driven Laravel' to learn TDD. As part of it I want to implement a follower-following relationship and https://stackoverflow.com/questions/44913409/laravel-follower-following-relationships/44913501
App/User.php
class User extends Authenticatable
{
// users that are followed by this user [user->]
public function following() {
return $this->belongsToMany(User::class, 'followers', 'follower_id', 'following_id');
}
// users that follow this user [->user]
public function followers() {
return $this->belongsToMany(User::class, 'followers', 'following_id', 'follower_id');
}
}
Users Schema
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('username');
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Followers schema
Schema::create('followers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('follower_id')->unsigned();
$table->integer('following_id')->unsigned();
$table->timestamps();
});
FollowOtherUsersTest.php
$userSan = factory(User::class)->create();
$this->actingAs($userSan)
->json('POST', 'following', ['username' => 'johndoe']);
FollowingController@store
// Get the username through request and find that user.
$userJohn = User::where('username', request('username'))->firstOrFail();
// Attach the user to the logged in user
Auth::user()->following()->attach($userJohn);
// Get the following user
$myFollowers = Auth::user()->followers()->get();
dd($myFollowers); // Expected to return $userJohn
The queries generated is as follows:
[2020-01-08 09:48:21] local.INFO: insert into "users" ("username", "password", "remember_token", "updated_at", "created_at") values (?, ?, ?, ?, ?) ["collins.bertha","yIXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi","SXcZIUHjqj","2020-01-08 09:48:21","2020-01-08 09:48:21"]
[2020-01-08 09:48:21] local.INFO: insert into "users" ("username", "password", "remember_token", "updated_at", "created_at") values (?, ?, ?, ?, ?) ["johndoe","yIXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi","NcbXaRBhoz","2020-01-08 09:48:21","2020-01-08 09:48:21"]
[2020-01-08 09:48:21] local.INFO: select * from "users" where "username" = ? limit 1 ["johndoe"]
[2020-01-08 09:48:21] local.INFO: insert into "followers" ("follower_id", "following_id") values (?, ?) [1,2]
[2020-01-08 09:48:21] local.INFO: select "users".*, "followers"."following_id" as "pivot_following_id", "followers"."follower_id" as "pivot_follower_id" from "users" inner join "followers" on "users"."id" = "followers"."follower_id" where "followers"."following_id" = ? [1]
Database used to create these tables is Sqlite. When I print the $myFollowers it is empty. What is wrong in this code?
Regards, Saneesh.
Please or to participate in this conversation.