Support the ongoing development of Laravel.io →
Database Eloquent Views

I'm trying to create table that I can store email preferences for each user. So far I've created a email_preferences table like so:

id PK
user_id FK
newsletter Boolean
updated_at
created_at

I'm trying to create a relationship between my User model and EmailPreferences model, but I'm having a rough go of if.

User:

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = array('password', 'remember_token');

    public function email_preferences()
    {
        return $this->hasOne('EmailPreference');
    }

}

EmailPreference:

class EmailPreference extends Eloquent {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'email_preferences';

    public function user()
    {
        return $this->belongsTo('User');
    }

}

I've tried to access the email preferences with:

$user = Auth::user();
echo '<pre>';
print_r($user->email_preferences);
exit;

But I get nothing... I get a non-object errors. Perhaps I'm going about this all wrong.

Last updated 3 years ago.
0

Change your email preferences function

public function emailPreferences()
{
    return $this->hasOne('EmailPreference');
}

Then update your call

$user = Auth::user();
echo '<pre>';
print_r($user->emailPreferences);
exit;

When you call $user->email_preferences, Eloquent will try and call $user->emailPreferences() but because this method doesn't exist, it'll return null. See here for more info.

0

Yup! That was the issue. That's pretty annoying ...

0

Sign in to participate in this thread!

Eventy

Your banner here too?

dcolumbus dcolumbus Joined 29 Dec 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.