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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

{<br />

}<br />

public function students()<br />

{<br />

return $this->has_many_and_belongs_to('Student');<br />

}<br />

We have two models, each with the same type of relationship to each other. has_many_and_<br />

belongs_to is a long name. But, it's a fairly simple concept. A course has many students.<br />

But, it also belongs to (belongs_to) student records and vice-versa. In this way, they are<br />

considered equal.<br />

Let's look at how we'll interact with these models in practice:<br />

$student = Student::find(1);<br />

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

{<br />

echo "The student can't be found.";<br />

exit;<br />

}<br />

if(!$student->courses)<br />

{<br />

echo "The student $student->name is not enrolled in any<br />

courses.";<br />

exit;<br />

}<br />

foreach($student->courses as $course)<br />

{<br />

echo "The student $student->name is enrolled in the course<br />

$course->name.";<br />

}<br />

Here you can see that we can loop through the courses much the same way we could with the<br />

one-to-many relationship. Any time a relationship includes the word many, you know that you'll<br />

be receiving an array of models. Conversely, let's pull a course and see which students are a part<br />

of it.<br />

$course = Course::find(1);<br />

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

{<br />

echo "The course can't be found.";<br />

exit;<br />

33

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

Saved successfully!

Ooh no, something went wrong!