Skip to content

Instantly share code, notes, and snippets.

@laracasts
Last active January 27, 2016 13:08
Show Gist options
  • Save laracasts/f797e671a0aa7143006a to your computer and use it in GitHub Desktop.
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?
<?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();
}
}
@jtgrimes
Copy link

@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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment