-
-
Save muhamed-didovic/959c2306915b090b549f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // Option 1: the follow method immediately references the relationship and saves it. | |
| class User extends Eloquent { | |
| public function follows() | |
| { | |
| return $this->belongsToMany(self::class, 'follows', 'follower_id', 'followed_id'); | |
| } | |
| public function follow($userIdToFollow) | |
| { | |
| return $this->follows()->attach($userIdToFollow); | |
| } | |
| } | |
| // Option 2: The follow method just stores an array of follow ids, which you can save later. | |
| class User extends Eloquent { | |
| public $follows = []; // public just for example | |
| public function follows() | |
| { | |
| return $this->belongsToMany(self::class, 'follows', 'follower_id', 'followed_id'); | |
| } | |
| public function follow($userIdToFollow) | |
| { | |
| $this->follows[] = $userIdToFollow; | |
| return $this; | |
| } | |
| } | |
| // And then, maybe in your repository: | |
| class EloquentUserRepository { | |
| public function save(User $user) | |
| { | |
| if ( ! empty($user->follows)) | |
| { | |
| $user->follows()->attach($user->follows); | |
| } | |
| return $user->save(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment