0

I would like to known how to get data from database in blade like from User table:

{{ Auth::user()->name }}

I have table user_settings

I would like to get record from this table by logged user id like this:

{{ UserSettings::user()->my_field }} 

How can I do that?

4
  • 1
    try {{ UserSettings::user()->my_field ->get()}} Commented Aug 17, 2017 at 16:07
  • return view("your view", ["userSettings" =>UserSettings::user()]); now $userSettigs is available in your view Commented Aug 17, 2017 at 16:10
  • 2
    DO not make database calls from your view layer, pass the data from the controller Commented Aug 17, 2017 at 16:15
  • Yes, but I must get one field in my header panel? When this panel are inclued in layout. Commented Aug 17, 2017 at 21:34

2 Answers 2

3

Try this on your blade view

{{ \App\UserSettings::where('user_id',Auth::user()->id)->first()->my_field }} 

In default, model file is inside App folder.

Such direct access to database table is not preferred though, you can return this as a variable from controller function like,

$field = \App\UserSettings::where('user_id',Auth::user()->id)->first()->my_field;  
return view('view_name',comapact('field'));

and use in blade like

{{$field}}

Another good way is posted by Orkhan in another answer using eloquent relationship. Hope you understand.

Sign up to request clarification or add additional context in comments.

4 Comments

Yes, but in my UserSettings model I don't have user() function and I gets Call to undefined method Illuminate\Database\Query\Builder::user()
Did you have user_id on user setting table ?
Yes I have this field
@lukassz So please close the question by accepting it
2

You need to retrieve the UserSettings associated to the authenticated user:

UserSettings::where('user_id', Auth::id())->first()->my_field

You can defined a method named current() to return that for you.

class UserSettings extends Model
{
    public static function current()
    {
        return UserSettings::where('user_id', Auth::id())->first()
    }
}

Then use:

UserSettings::current()

On the other had it would better to use one-to-one relationship on user model:

class User extends Model
{
    public function settings()
    {
        return $this->hasOne('App\UserSettings');
    }
}

Then use:

Auth::user()->settings->my_field

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.