0
votes

I'm refreshing my knowledge about Laravel eloquent relationships. Unfortunately, i'm unable to solve/find a problem with a one to many relationship. Someone any idea/suggestion what is wrong with my code?

What is happening

Eloquent does not find any related data from the mobiles table. Current result (pastebin)

What should happen

Getting all related data from the mobile table.

Involved code

I'm working on a clean Laravel 5.4 installation. This is the only code i created/added.

User model

public function phone(){

    return $this->hasMany('App\Mobile', 'user_id', 'id');

}

With this function eloquent will get all records from the mobile table where column user_id == id right?

User table

Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });

Mobile table

 Schema::create('mobiles', function (Blueprint $table) {
        $table->increments('id');

        $table->integer('user_id');

        $table->string('phoneNumber');

        $table->timestamps();
    });
2
And in your Mobil model use public function user() { return $this->belongsTo('App\User'); } and add $table->foreign('user_id')->references('id')->on('users'); in the mobiles migrationMaraboc
Thank you, unfortunately it doenst work. I will start learning eloquent relationships again.Romano Schoonheim
How are you fetching the results? What's the query?Omar Tarek
I select a user using User::find(); i call ->phone(); on the result of find.Romano Schoonheim

2 Answers

0
votes

Depending on your codes, I think the problem lies in your model. It should be like as follows:

User table

protected $fillable=['name', 'email' , 'password'];

public function Mobile(){

    return $this->hasMany(Mobile::class);

}

Mobile table

protected $fillable=['user_id', 'phonenumber'];

public function User(){

    return $this->hasMany(User::class);

}

You need to specify either a fillable or guarded attribute on the model, as all Eloquent models protect against mass-assignment by default.

Given that you are calling correctly from database, this should work.

0
votes

As suggested by @Maraboc in the comments section, create a user function with the content

public function user(){
    $this->belongsTo(User::class);
}

This solved my problem