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

Haseeb69's avatar

Get detailed information on record

i have three tables Permit ( pid, userid , companionid) , User(id,name etc) , Companion(cid, userid1,userid2,userid3,userid4 which are foreign keys to user table)

here are my relations in models

Permit:

    public function user()
    {
    return $this->belongsto(User::class,'userid','id');       
    }
    public function companion()
    {
    return $this->belongsto(Companion::class,'companionid','comid');        
    }

User:

  public function permits()
    {
        return $this->HasMany(Permit::class,'id','userid');
    }
    public function companions()
    {
        return $this->HasMany(Companion::class,'id','userid1')->HasMany(Companion::class,'id','userid2')->HasMany(Companion::class,'id','userid3')->HasMany(Companion::class,'id','userid4');
    }

Companion:

    public function permit()
    {
        return $this->HasMany(Permit::class,'comid','companionid');
    }
    public function user()
    {
    return $this->belongsto(User::class,'userid1','id')
    ->belongsto(User::class,'userid2','id')
    ->belongsto(User::class,'userid3','id')
    ->belongsto(User::class,'userid4','id');        
    }

The response i get from running this eloquent query

    $userinfo = Permit::with('user')->with('companion')->with('user')->where('pid', $pid)->where('userid', $id)->first();
            return $userinfo;
    

json response

{
pid: 14,
userid: "12345",
timeofvisit: "22:36:00",
dateofvisit: "2021-04-15",
registrationtype: "No Vehicle",
companionid: 2,
user: {
	id: "12345",
	idtype: "Citizen",
	usertype: 0,
	phone: "92213123123",
	fname: "xyz",
	DOB: "2021-04-21"
	},
companion: {
	comid: 2,
	userid1: "1",  i want this detailed info 
	userid2: "2",  i want this detailed info
	userid3: "3",  i want this detailed info
	userid4: null  
}
}

please look at the json response and tell me how can i achieve that Also i know my relations are really bad and i need suggestions on improving p,s no hate im a newbie

0 likes
1 reply
reaz's avatar

You need to define relationship on Companion Model for each user1 , user2 , user4 . Otherwise eloquent would not know how relate those information to the user table.

Please or to participate in this conversation.