FilamentF
Filament16mo ago
ericmp

Convert model method to eloquent relationship

imagine this scenario
tables:
Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->foreignIdFor(Task::class)->constrained();
});

Schema::create('tasks', function (Blueprint $table) {
    $table->id();
});

eloquent relations:
class User extends Authenticatable
{
    public function tasks(): BelongsToMany
    {
        return $this->belongsToMany(Task::class);
    }
}

class Task extends Model
{
    public function users(): HasMany
    {
        return $this->hasMany(User::class);
    }

    public function latestUser(): HasOne
    {
        return $this->hasOne(User::class)->latestOfMany();
    }

    public function oldestUser(): HasOne
    {
        return $this->hasOne(User::class)->oldestOfMany();
    }
}

right now, using only eloquent relations, i can know which is the latest and also which is the oldest user linked to the task.

this is how it would look like the task model but wrong for this case, since they return ?User, but as i said, i need the methods to return eloquent relationships:
class Task extends Model
{
    public function users(): HasMany
    {
        return $this->hasMany(User::class);
    }

    public function latestUser(): ?User
    {
        return $this->users()->orderBy('users.created_at', 'desc')->orderBy('users.id', 'desc')->first();
    }

    public function oldestUser(): ?User
    {
        return $this->users()->orderBy('users.created_at', 'asc')->orderBy('users.id', 'asc')->first();
    }
}

as you have noticed this is a has many relationship. and it works fine.

but my question is how to translate this into a belongs to many relationship.
as in the has many relationship case, for the belongs to many relationship i want:
  • to be able to retrieve task's users as an eloquent relationship
  • to be able to retrieve task's first user as an eloquent relationship
  • to be able to retrieve task's oldest user as an eloquent relationship
Was this page helpful?