Stefano Montevecchi
Stefano Montevecchi

Reputation: 1

Laravel - How use HasMany

I have a little problem with model relationships.

I have a Users table and a Appartaments table, with a hasmany relationship linked from the ref_user field(Users) to the agent field(Appartaments). Neither is a primary key.

In my User model I have:

    public function appartaments(){
    return $this->hasMany(Appartament::class,'agent','ref_user');
}
public function idAppartaments($id){
    return User::find($id)->appartaments;
}

In my controller I have:

public function getAppUser($ref_user){
    $id = User::select('id')->where('ref_user',$ref_user)->get();
    $appartaments = User::idAppartaments($id);
    return $appartaments;

When I try the route however, I get an error that the appartaments property does not exist.

Upvotes: 0

Views: 507

Answers (2)

Marwane Ezzaze
Marwane Ezzaze

Reputation: 1057

This is the proper way to do so: in your User Model:

public function appartaments(){
    return $this->hasMany(Appartament::class,'agent','ref_user');
}

in your controller:

public function getAppUser($ref_user){
    $user = User::with('appartaments')->where('ref_user',$ref_user)->first();
    $appartaments = $user ? $user->appartaments : null;
    return $appartaments;
}

Upvotes: 1

calebe santana
calebe santana

Reputation: 335

Instead of your controller method:

public function getAppUser($ref_user){
$id = User::select('id')->where('ref_user',$ref_user)->get();
$appartaments = User::idAppartaments($id);
return $appartaments;

The method should be:

public function getAppUser($ref_user){
$id = User::select('id')->where('ref_user',$ref_user)->get();
$appartaments = $id->appartaments();
return $appartaments;

Upvotes: 0

Related Questions