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

Ab.net's avatar

How can i fetch a data from 3 tables with relationship

i wanted to fetch a data from 3 tables with relationship but it is not working for me and i needed help.

my tables are

  1. Users table

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

  1. Countries table

     Schema::create('countries', function (Blueprint $table) {
         $table->increments('id');
         $table->string('name_en');
         $table->string('name_fr');
         $table->string('short_code');
         $table->string('id_region');
         $table->timestamps();
         $table->softDeletes();
     });
    
  2. food_and_feeds table

Schema::create('food_and_feeds', function (Blueprint $table) { $table->increments('id'); $table->string('Sample_code'); $table->string('Latitude'); $table->string('Longitude'); $table->unsignedInteger('users_id')->nullable(); $table->foreign('users_id')->references('id')->on('users'); $table->timestamps(); $table->softDeletes(); });

My models

  1. User Model

public function country() {

    return $this->belongsTo('App\Country');
}

public function food_and_feed()

{

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

}

  1. Country Model

public function users(){

    return $this->hasMany('App\User','country_id');
}
  1. Food and feed model

public function users(){

    return $this->belongsTo('App\User','users_id','id');
}

i can fetch the user_id from my food and fed relation ship but i wanted to fetch the user country through its id from the relationship in food and feeds view.

i can fetch the users name using this

                                    <td> {{$food->users->name}} </td>

but i want to fetch the users country name

how can i do this? thanks in advance.

0 likes
1 reply
tinfoilman's avatar

Do you have a country_id in your users table? It doesn't look like it, and I think you need one in order for the public function country() to work in your User Model.

1 like

Please or to participate in this conversation.