21.11.2014 Views

Laravel Starter - PHP User Group (Myanmar)

Laravel Starter - PHP User Group (Myanmar)

Laravel Starter - PHP User Group (Myanmar)

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Laravel</strong> <strong>Starter</strong><br />

class Player extends Eloquent<br />

{<br />

public function team()<br />

{<br />

return $this->belongs_to('Team');<br />

}<br />

}<br />

This example is almost identical to the one-to-one example. The only difference is that<br />

the team's players() relationship uses has_many() rather than has_one(). The<br />

has_one() relationship returns a model object. The has_many() relationship returns<br />

an array of model objects.<br />

Let's display all of the players on a specific team:<br />

$team = Team::find(2);<br />

if(is_null($team))<br />

{<br />

echo "The team could not be found.";<br />

}<br />

if(!$team->players)<br />

{<br />

echo "The team has no players.";<br />

}<br />

foreach($team->players as $player)<br />

{<br />

echo "$player->name is on team $team->name. ";<br />

}<br />

Again, we test to make sure that our team could be found. Then, we test to make sure that<br />

the team has players. Once we know that for sure, we can loop through those players and<br />

echo their names. If we tried to loop through the players without first testing and if the team<br />

had players, we'd get an error.<br />

31

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!