skip to Main Content

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


  1. 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:

    class Lesson extends Model
    {
      public function activeUsers()
      {
        return User::where('is_active', true)->get();
      }
    }
    

    Why It’s Not Recommended:

    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.

    Recommended Approach

    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:

    class User extends Model
    {
       public function scopeActive($query)
       {
           return $query->where('is_active', true);
       }
    }
    

    Then, in your controller or service, you can do:

    $activeUsers = User::active()->get();
    
    Login or Signup to reply.
  2. You can append a new property to the Lesson model:

    class Lesson extends Model
    {
        protected $appends = ['users'];
    
        public function getUsersAttribute()
        {
            return User::where('is_active', true)->get();
        }
    }
    

    Now, the users key will be included in all lesson records.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search