Pinky Yknip
Pinky Yknip

Reputation: 21

want to view logged user company name, not id

I have two related Tables $table->foreignId('company_id')->references('id')->on('companies');

users Table companies Table
id id
company_id name
Second

in view I want to show logged user company name

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

pls help : (

Upvotes: 0

Views: 246

Answers (2)

ruleboy21
ruleboy21

Reputation: 6391

You can use this code

{{Company::find(Auth::user()->company_id)->name}}

where Company is your company's model or you can define a one-to-one relationship in your User model like so

/**
 * Get the company associated with the user.
 */
public function company()
{
    return $this->belongsTo(Company::class);
}

And use it like this

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

Upvotes: 0

Nicolas Hedger
Nicolas Hedger

Reputation: 166

Assuming that many users can belong to a company, you'll want to define a One to Many relationship between your User and Company models.

On your User model, add the following method.

public function company()
{
    return $this->belongsTo(Company::class);
}

Retrieving the name of the company for the currently logged-in user is done like so.

$name = Auth::user()->company->name;

Upvotes: 1

Related Questions