0

I have a problem with my relations in laravel: I have two tables, Languages and Customers.The customer just can have 1 language. These are my migrations and Models:

Migrations:

   Schema::create('tbl_customers', function (Blueprint $table){
        $table->increments('id');
        $table->string('first_name',255);
        $table->string('last_name',255);
        $table->date('date_of_birth');
        $table->string('email',255);
        $table->string('phone_number',255);
        $table->string('phone_number2',255);
        $table->string('password', 255);
        $table->unsignedInteger('dealer_id');
        $table->string('picture_profile',255);
        $table->string('occupation',255);;
        //Foreign key
        $table->unsignedInteger('language_id');
        $table->string('about_me',255);
    });

  Schema::create('tbl_languages', function (Blueprint $table){
        $table->increments('id');
        $table->string('language',255);
    });

This is the foreign Key:

Schema::table('tbl_customers', function (Blueprint $table){
        $table->foreign('language_id')->references('id')
            ->on('tbl_languages')->onDelete('cascade');
    });

These are my Models. Customer:

class Customer extends Model{
protected $table='tbl_customers';
protected $primaryKey="id";
protected $fillable=['address_id','first_name','last_name','gender_id','date_of_birth','email','phone_number','phone_number2',
                    'dealer_id','picture_profile','occupation','time_zone_id','language_id','about_me'];
protected $hidden=['password'];
public $timestamps = false;

public function language(){
    return $this->hasMany(Language::class);
}}

Language

class Language extends Model{
protected $table='tbl_languages';
protected $primaryKey="id";
protected $fillable=['language'];
public $timestamps=false;

public function customers(){
    return $this->belongsToMany(Customer::class);
}}

So, If I make a query I have the next error:

error

why? If the migrations have the standard that Laravel says

If I change the Customer model like this:

public function language(){
    return $this->hasMany(Language::class,'id','language_id');
}

It works good, but Languages no.

I wish you guys can help me.

Angel Mora
  • 43
  • 1
  • 5
  • 1
    Ok, you say *"The customer just can have 1 languages."* but you're defining a `languages()` Relationship, instead of a `language()` Relationship, and using `return $this->hasMany(Language::class);` instead of `return $this->hasOne(Language::class)`... – Tim Lewis Jun 14 '18 at 20:40

1 Answers1

1

add this to your Customer model:

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

and this to your Language model:

public function customers(){
  return $this->hasMany('App\Customer');
}
Hussein
  • 1,143
  • 1
  • 9
  • 16