lukassz
lukassz

Reputation: 3340

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?

Upvotes: 0

Views: 10065

Answers (2)

Sagar Gautam
Sagar Gautam

Reputation: 9359

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.

Upvotes: 3

Orkhan Alikhanov
Orkhan Alikhanov

Reputation: 10050

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

Upvotes: 2

Related Questions