Search code examples
phplaravel-4eloquentmany-to-many

Simple way to check if user is a friend in Laravel 4


I'm trying to easily check if a given user_id is a friend of the current user so I can simply do a check within a blade @if statement. My friendship functionality is two-way, and accepting a friendship is not required.

I have seem to have some setup going, but am not confident that I'm doing it properly.

Friendship Table

Schema::create('friendshipLinks', function ($table) {
    $table->increments('id');
    $table->integer('userId_1'); // foreign key
    $table->integer('userId_2'); // foreign key

    $table->timestamps();

    $table->foreign('userId_1')->references('id')->on('users')->onDelete('cascade');
    $table->foreign('userId_2')->references('id')->on('users')->onDelete('cascade');
});

User Model (Trimmed)

class User extends Eloquent implements UserInterface, RemindableInterface {

    use EloquentTrait, UserTrait, RemindableTrait;
    protected $table = 'users';

    // RELATIONSHIPS
    public function posts() {
        return $this->hasMany('Post');
    }

    // FRIENDSHIP
    function friends() {
        return $this->belongsToMany('User', 'friendshipLinks', 'userId_1', 'userId_2');
    }

    function friendsWith() {
        return $this->belongsToMany('User', 'friendshipLinks', 'userId_2', 'userId_1');
    }
}

Friendship Model

class Friendship extends Eloquent {
    protected $table = 'friendshipLinks';
    protected $fillable = ['userId_1', 'userId_2'];
}

At the moment I can get an array of all the users friends with (Two-way)

$friends = User::find($id)->friends;
$friendsWith = User::find(Auth::user()->id)->friendsWith;
$result = $friends->merge($friendsWith);

How can I easily implement something that will allow me to call a function that return a boolean like:

$isFriend = User::find($id)->isFriend($friend_id);

Solution

  • Here is the solution method in user model's class:

    public function isFriend($friendId) {
        return (boolean) $this->friends()->where('users.id', $friendId)->count();
    }