getting data using Eloquent/one to many relationship

Posted 1 year ago by [email protected]

Hi .

i have two table: 1-country 2-customers

the relationship between two table is one to many. as Example: for one country we have many customers.

Country model:

class Country extends Model

    protected $table="country";
    protected $primaryKey="country_id";
    public function customer(){

        //return null;
       return $this->hasMany("App\Customer",'country_fid','country_id');


Customer model:

 class Customer extends Model
    protected $table="customer";
    protected $primaryKey="customer_id";
    public function country(){

        return $this->belongsTo("App\Country",'country_fid','country_id');
    }//country function

using below code i can get customers data but i can not get country list related to customer. in fact i want to get name of country related to only give me customers information:


    foreach($customers as $customer){

        echo $customer->customer_id."|".$customer->customer_name."|".$customer->country_fid."<br/>";
        foreach($customer->Country as $country){
            echo $country->country_name."<br/>";



Please sign in or create an account to participate in this conversation.