class User extends Model
{
public function projects(): BelongsToMany
{
return $this->belongsToMany(Project::class);
}
}
class Project extends Model
{
public function scopeActive(Builder $query): void
{
$query->where('active', 1);
}
}
dump(User::find(1)->projects()->active()->get());
Sometimes a model may have many related models, yet you want to easily retrieve the "latest" or "oldest" related model of the relationship. For example, a User model may be related to many Order models, but you want to define a convenient way to interact with the most recent order the user has placed. You may accomplish this using the hasOne relationship type combined with the ofMany methods:
public function project(): HasOne
{
$instance = $this->newRelatedInstance(Project::class);
$relation = new HasOne($instance->newQuery(), $this, DB::raw('project_user.user_id'), $this->getKeyName());
return $relation->leftJoin('project_user', 'project_user.project_id', '=', 'projects.id');
}