I have a User and Lesson models. these models are not related to each other.
users table: id, username, password, is_active
lessons table: id, title
User
class User extends Modle
{
// code
}
Lesson
class Lessosn extends Modle
{
public function users()
{
// I need to return all users here where is_active=true as RELATIONSHIP
// return User::where('is_active', true);
}
}
In the Lesson model I want to have a relationship to load users where (is_active, true)
So I can list all users where is_active = true
Thanks
2
Answers
Since there’s no actual foreign key relationship between Lesson and User, you need to create a custom method instead of a standard Eloquent relationship:
Lack of Integrity: Since there’s no real foreign key relationship, you lose referential integrity. Laravel’s built-in relationship methods like hasMany, belongsTo, etc., won’t function as intended.
Limited Query Builder Features: Standard relationships in Laravel provide you with powerful features like eager loading (with), query constraints on related models, and lazy loading. A custom method like activeUsers doesn’t integrate with these features.
Maintainability: This approach could lead to confusion for others (or even yourself in the future) who might expect a traditional relationship when they see a method named activeUsers. They might assume it’s a standard relationship method, which it is not.
Use a Scope or Repository: If the relationship is purely logical and you need to filter users based on a condition like is_active, consider using a query scope in the User model or a repository pattern to handle this logic instead of placing it in the Lesson model.
Example:
Then, in your controller or service, you can do:
You can append a new property to the
Lesson
model:Now, the
users
key will be included in all lesson records.