Skip to content

Instantly share code, notes, and snippets.

@muhamed-didovic
Forked from laracasts/ex.php
Last active August 29, 2015 14:11
Show Gist options
  • Select an option

  • Save muhamed-didovic/959c2306915b090b549f to your computer and use it in GitHub Desktop.

Select an option

Save muhamed-didovic/959c2306915b090b549f to your computer and use it in GitHub Desktop.
<?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