Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

appyapp's avatar

User, Prefs, UserPrefs - How to retrieve all UserPrefs with Prefs.name for a User?

I have these three tables.

Accounts

  • id
  • name
  • email
  • organisation_id

Preferences

  • id
  • name

Data example,

  • 1, Morning Only, 1445
  • 2, Afternoons Only, 1445
  • 3, Evenings Only, 1445
  • 4, Red color Only, 1240
  • 5, Cars Only, 1240

AccountPreferences

  • id
  • account_id
  • preference_id
  • mandatory ('Yes', 'No')

I want to access all account preferences of a user.

class Account extends Model
{
    public function preferences()
    {
        return $this->hasMany('App\AccountPreference', 'account_id', 'id'); //model, foreign_key, local_key
    }
}
class Preference extends Model
{
  // just default empty model class
}
class AccountPreference extends Model
{
 // just default empty model class
}

When I do

$account = Account::find(134);
$pref = $account->preferences()->get();
dd($pref);

When I do $pref = $account->preferences()->get(); I want to retrieve preference name from preferences table too.

How do I do that?

Thanks

0 likes
4 replies
appyapp's avatar

@EMILVENKOV12 - Thanks but a preference doesn't belong to any user. Only AccountPreference has an account_id to link with a user and preference_id to link with a preference.

appyapp's avatar

I have also added this in my App/AccountPreference.php

class AccountPreference extends Model
{
    public $appends = ['pref_name'];

    public function getPrefNameAttribute()
    {
        return $this->prefName()->first();
    }
    public function prefName()
    {
        return $this->belongsTo('App\Preference', 'preference_id');
    }
}

but still not sure how to get it working.

emilVenkov12's avatar

Let me apologies at first i misunderstood your question, with further review on your previous comments i think you need the add code similar to the one i wrote to your App\Preference model so will be able to make the relationship with App\Account and therefore to access the every account's Preferences with: $pref = $account->preferences()->get();

Please or to participate in this conversation.