简体   繁体   中英

Laravel get record from database in blade view

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM