Search code examples
laravelormeloquentrelationshipforeign-key-relationship

Correctly use Eloquent relationships


I am developing a Laravel 4 application with 4 database tables:

  • Therapist
  • TherapistType
  • Municipality
  • County

I'm using foreign keys to reference the data from other tables. The relationships are the following:

  • A therapist can have one therapist type, municipality and county
  • A therapist type and municipality can belong to many therapists.
  • A municipality can have one county.
  • A county can belong to many municipalities and therapists.

I'm using Eloquent ORM.

This is the code I tried to use:

Therapist model:

public function therapistType() {
        return $this->belongsTo('TherapistType');
    }

    public function municipality() {
        return $this->hasOne('Municipality');
    }

    public function county() {
        return $this->hasOne('County');
    }
}

Municipality model:

public function county() {
        return $this->hasOne('County');
    }

In my controller I use the following code to fetch the therapists:

$therapists = Therapist::paginate(10);
return View::make('index', compact('therapists'));

And finally in my view this is how I'd like to get the corresponding therapist type for a therapist:

<span class="therapisttype">{{{ $therapist->therapistType  }}}</span>

However I get no data.

What am I doing wrong?


Solution

  • $therapist->therapistType should be returning an object, but you are not echoing the property of said object. Let us just imagine that the therapistType table has a name property, then you should do

    {{$therapist->therapistType->name}} if you want to echo that name.

    I would begin by var_dumping the object, you can use $therapist->therapistType assuming that you have the relationships set up correctly, you should be able to see all it's properties.

    Hope it helps.