//Models
//app/Town.php
<?php namespace App;
use Illuminate\Database\Eloquent\Model as Eloquent;
class Town extends Eloquent {
public function state()
{
return $this->belongsTo('App\State');
}
}
//app/State.php
<?php namespace App;
use Illuminate\Database\Eloquent\Model as Eloquent;
class State extends Eloquent {
public function towns()
{
return $this->hasMany('App\Town');
}
}
//Controller
$california = State::find(2);
//View
@foreach($california->towns as $town)
{{ $town->name }}
@endforeach
Feb 3, 2015
9
Level 1
Basic overview of querying relationships with eloquent
With help from the community here I have finally been able to query the results of a table with eloquent. As a next step, I was hoping to get some help querying a simple relationship. I've tried some tutorials but I'm getting errors and there are parts I'm just not understanding. I have two tables:
towns
+---------+------------------------+-----------------+
| id (PK) | name | state_id (FK) |
+---------+------------------------+-----------------+
| 1 | Los Angeles | 2 |
| 2 | Seattle | 3 |
| 3 | Portland | 1 |
| 3 | San Francisco | 2 |
+----------------------------------+-----------------+
states
+---------+------------------------+
| id (PK) | name |
+---------+------------------------+
| 1 | Oregon |
| 2 | California |
| 3 | Washington |
+----------------------------------+
Can someone show me what the models would look like and how to display all the towns that belong to California?
Please or to participate in this conversation.