2
votes

I have three database tables called user(id,name), group(id,name) and user_group(user_id, group_id,valid_before) with relations many to many.

class User extends Model
{
    protected $table = 'user';

    public function groups()
    {
    return $this->belongsToMany(Group::class, 'user_group')
        ->withPivot('valid_before');
    } 
}

class Group extends Model
{
    protected $table = 'group';

    public $timestamps = false;

    public function user()
    {
        return $this->belongsToMany(User::class, 'user_group');
    }
}

User can be member of some group until time moment 'valid_before'. If 'valid_before' is less than current time, the user must be excluded from the group and corresponding row in pivot table must be deleted. How can I select in pivot table rows where strtotime($validBefore) < strtotime($date) and then delete them using Eloquent?

1

1 Answers

2
votes

use cronjob then simply use detach($group_id) like below:-

$user = User::find($id);
if(time_exceeded($user->id))  //checks if user should stay in a group
$user->groups()->detach($group_id);

use this link for refernce