Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

david2000's avatar

Display the connected customer information

I have 2 tables which are user and customer, la first table has like fields following:

(id, name, email, password).

Then, the table 'customer' has like fields (id, name, firstname).

In my Controller Customer, via my function index(), I have to retrieve id_user from my table user.

1 question // is it my relationship is correct between my 2 tables?

Model Customer

protected  $fillable = ['name', 'firstname', 'user_id'];

public function user()
{
        return $this->belongsTo('App\User');
}

Model User

public function customers()
{
        return $this->hasOne('App\Customer');
}

2 question // How retrieve ID of the user which is connected ?

I have for now this only...


public function index()
{
        $customers = Customer::orderby('id', 'desc')->paginate(5);
        return view('customers.index', compact('customers'));
}

3 question // I wait to understand the answer two, but I would like to understand. How I have to adapt my file index.blade.php via my loop please?

@foreach($customers as $customer)
 <tr>
   <td> {{$customer->name}}</td>
    <td> {{$customer->firstname}}</td>

Thank you for your explanations.

0 likes
3 replies
bigM's avatar
bigM
Best Answer
Level 15

The Customer table should have a user_id field. e.g. [id, user_id, name, firstname]

Then the Customer model automatically looks for User::id in relationship. see doc

Customer model relationship

public function user()
{
    return $this->belongsTo('App\User');
}

User model relationship

public function customer() // <= not customer[s] for hasOne
{
    return $this->hasOne('App\Customer');
}

If User::id and Customer::id are suppose to be related, You can specify keys without having a user_id field in the Customer table.

Customer model relationship

public function user()
{
    return $this->belongsTo('App\User', 'id', 'id');
}

User model relationship

public function customer() // <= not customer[s] for hasOne
{
    return $this->hasOne('App\Customer', 'id', 'id');
}
Snapey's avatar

please mark best answer if it solved your problem

Please or to participate in this conversation.