Chud37
Chud37

Reputation: 5007

Load user settings with Laravel 5.6

I'd like to be able to modify the Auth->user() data that Laravel 5.6 uses. I have table called settings with a column called user_id in it that corresponds to a user id.

I tried modifying app\User.php and adding a __construct function:

   public function __construct() {

        $this->settings = Settings::where('user_id',
                Auth->user->id()
                )->first();
    }

And I created a file app\Settings.php with the following:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class settings extends Model
{
    protected $table = "settings";

}

However I'm getting a user error on the Auth->user()->id line in User.php, although I'm sure thats the correct way to reference it?

How can I load the data from the settings table to the User class?

Upvotes: 2

Views: 1299

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163838

You can just use load() method to lazy load the relation:

auth()->user()->load('settings');

You need to do this just once per request, in a middleware for example. Then you'll be able to use the data in any part of your app:

{{ auth()->user()->settings->theme }}

Of course, to make this work you need to define relationship in the User model, for example:

public function settings()
{
    return $this->hasOne(Settings::class);
}

Upvotes: 5

Related Questions