Hey guys, I have two eloquent models:
User:
<?php namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
protected $dates = ['birthday'];
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
public function connections()
{
return $this->belongsToMany('App\Connection');
}
public function addConnection(Connection $connection)
{
$this->connections()->attach($connection->id);
}
public function removeConnection(Connection $connection)
{
$this->connections()->detach($connection->id);
}
public static function boot()
{
parent::boot();
User::deleting(function($user)
{
$user->connections()->detach();
});
}
}
Connection:
<?php namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class Connection extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
protected $dates = ['birthday'];
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'connections';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name', 'email', 'image', 'gender', 'phone', 'company', 'function', 'social', 'address', 'city', 'postcode', 'birthday'];
public function post()
{
return $this->belongsTo('App\User');
}
}
I have three tables, a table for users, one for connections and another one named connection_user, which has columns id, user_id and connection_id.
With the code below, I can successfully extract all connections related to a user:
$connections = $user->connections()->simplePaginate(6);
What if I wanted to do its reverse, getting all the users related to a connection? Is that possible at the current state?
Thanks.