admin管理员组

文章数量:1289845

I want to add a feature to my Laravel app that allows one user to follow another user. From the research that I've done I should be able to do this without a followings model. So what I do have is a follow_users pivot table with following schema

Schema::create('follow_users', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->onUpdate('cascade')->onDelete('cascade');
            $table->foreignId('follow_id')->constrained('users', 'id')->onUpdate('cascade')->onDelete('cascade');
            $table->timestamps();
        });

I understand I don't need the id or the timestamps but I would prefer to have them.

My routes are as follows:

Route::middleware('auth:sanctum')->prefix('v2')->group(function () {
    Route::apiResource('/follows', FollowController::class);
});

I have many more routes than this but only showing this for brevity. All my other routes work as expected.

For my Users model I have the following:

public function followings(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'follow_users', 'follow_id', 'user_id')->withTimestamps();
    }

I did create a FollowController in which I plan to hold my methods for index, store, show, update, delete. Where I'm getting lost is in the controller. For all of my other controllers I have something like

public function store(StoreCommentRequest $request)
    {
        $suggestion = Comment::create($request->validated());

        return CommentResource::make($suggestion);
    }

to store my data. But because I don't have a Follow model nor a FollowResource I can't do it the same way.

How do I code this using the User model to save the data to the pivot table?

I want to add a feature to my Laravel app that allows one user to follow another user. From the research that I've done I should be able to do this without a followings model. So what I do have is a follow_users pivot table with following schema

Schema::create('follow_users', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->onUpdate('cascade')->onDelete('cascade');
            $table->foreignId('follow_id')->constrained('users', 'id')->onUpdate('cascade')->onDelete('cascade');
            $table->timestamps();
        });

I understand I don't need the id or the timestamps but I would prefer to have them.

My routes are as follows:

Route::middleware('auth:sanctum')->prefix('v2')->group(function () {
    Route::apiResource('/follows', FollowController::class);
});

I have many more routes than this but only showing this for brevity. All my other routes work as expected.

For my Users model I have the following:

public function followings(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'follow_users', 'follow_id', 'user_id')->withTimestamps();
    }

I did create a FollowController in which I plan to hold my methods for index, store, show, update, delete. Where I'm getting lost is in the controller. For all of my other controllers I have something like

public function store(StoreCommentRequest $request)
    {
        $suggestion = Comment::create($request->validated());

        return CommentResource::make($suggestion);
    }

to store my data. But because I don't have a Follow model nor a FollowResource I can't do it the same way.

How do I code this using the User model to save the data to the pivot table?

Share Improve this question edited Feb 24 at 9:12 halfer 20.5k19 gold badges109 silver badges202 bronze badges asked Feb 20 at 1:17 Jamie HolcombJamie Holcomb 414 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 2

So what I ended up doing for this case is this. In my FollowController, for the store method I did this:

public function store(StoreFollowRequest $request, User $user) {
    $request->validated();
    $user = $request->user();
    $user->followings()->attach($request->follow_id);
    return UserResource::make($user);
}

To give you an idea, here's how I would implement it.

routes/api.php

Route::group(['middleware' => 'auth:sanctum', 'prefix' => 'users', 'as' => 'users.'], function () {
    Route::post('{user}/follow', [\App\Http\Controllers\UserController::class, 'follow'])->name('follow');
    Route::delete('{user}/follow', [\App\Http\Controllers\UserController::class, 'unfollow'])->name('unfollow');
});
↓
POST   /api/users/1/follow
DELETE /api/users/1/follow

Routes to follow and unfollow user ID 1.

The implementation would look something like this.

class UserController {
    public function follow(User $user)
    {
        $me = auth()->user(); // logged in user.

        // follow target user.
        $me->followings()->attach($user->a);

        return response()->noContent();
    }

    public function unfollow(User $user)
    {
        $me = auth()->user(); // logged in user.

        // unfollow target user.
        $me->followings()->detach($user->a);

        return response()->noContent();
    }
}

The followings() relation has a method called attach() and is specifically used for many to many relationships. Once you attach the followings, you can access them with $user->followings.

Take note, I didn't include any validations in this example.

Also, there's already a package for that and I think it's easy to use.

https://github/overtrue/laravel-follow

You can read more on many to many relationships in the laravel docs.

Hopefully you got a gist of the implementation.

本文标签: phpHow do I add a following api to my Laravel appStack Overflow