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 />

We created a method named passport() that returns a relationship. It might seem strange to<br />

return relationships at first. But, you'll soon come to love it for the flexibility it offers.<br />

You'll notice that we're using the has_one() method and passing the name of the model as a<br />

parameter. In this case, a user has one passport. So, the parameter is the name of the passport<br />

model class. This is enough information for Eloquent to understand how to acquire the correct<br />

passport record for each user.<br />

Now, let's look at the Passport class:<br />

class Passport extends Eloquent<br />

{<br />

public function users()<br />

{<br />

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

}<br />

}<br />

We're defining the passport's relationship differently. In the <strong>User</strong> class, we used the<br />

has_one() method. In the Passport class we used belongs_to().<br />

It's vital to identify the difference early so that understanding the rest of the relationships is<br />

more simple. When a database table contains a foreign key, it is said that it belongs to a record<br />

in another table. In this example, our passports table refers to records in the users table<br />

through the foreign key user_id. Consequently, we would say that a passport belongs to a<br />

user. Since this is a one-to-one relationship the user has one (has_one()) passport.<br />

Let's say that we want to view the passport number of the user with the id of 1.<br />

$user = <strong>User</strong>::find(1);<br />

If(is_null($user))<br />

{<br />

echo "No user found.";<br />

29

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

Saved successfully!

Ooh no, something went wrong!