Last active
January 27, 2016 13:08
-
-
Save laracasts/f797e671a0aa7143006a to your computer and use it in GitHub Desktop.
So you want to allow one user to "follow" another user (like Twitter-style). Using Laravel and Eloquent, what's your preference?
This file contains 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
@laracasts When I see "extends Eloquent," I expect relationships to be persisted and I think I expect that to be the default. That's just how Eloquent usually rolls.