Michele Della Mea
Michele Della Mea

Reputation: 1002

one to many relationship not working in Laravel

I am doing a project with Laravel. I would like to return the language of a customer... but for some reason I return an empty response. One customer can have only one language and one language can be spoken by many customers.

This is the model of Language:

public function customers()
    {
        return $this->hasMany('App\Customer', 'language_id', 'id');
    }

This is the model of Customer:

public function language()
{
    return $this->belongsTo('App\Language', 'id', 'language_id');
}

And this is what I tried to return:

return Customer::where('customer_id', $customerId)->first()->language()->pluck('language_id');

I should receive values like FR, IT, EN... but I receive only [].

Can help?

Upvotes: 0

Views: 32

Answers (1)

OMR
OMR

Reputation: 12218

I think the wrong in your relation in:

Customer Model:

public function language()
{
    return $this->belongsTo('App\Language',  'language_id','id');
}

like in doc the second parameter in the belongsTo should be the foreign_key column. and you can omit them if you followed Laravel convention for naming columns

Upvotes: 2

Related Questions