Laravel Starter - PHP User Group (Myanmar)
Laravel Starter - PHP User Group (Myanmar)
Laravel Starter - PHP User Group (Myanmar)
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 />
if(!$course->students)<br />
{<br />
echo "The course $course->name seems to have no students<br />
enrolled.";<br />
exit;<br />
}<br />
foreach($course->students as $student)<br />
{<br />
echo "The student $student->name is enrolled in the course<br />
$course->name.";<br />
}<br />
The relationship functions exactly the same way from the course side.<br />
Now that we have established this relationship, we can do some fun things with it. Let's look at<br />
how we'd enroll a new student into an existing course:<br />
$course = Course::find(13);<br />
if(is_null($course))<br />
{<br />
echo "The course can't be found.";<br />
exit;<br />
}<br />
$new_student_information = array(<br />
'name' => 'Danielle'<br />
);<br />
$course->students()->insert($new_student_information);<br />
Here we're adding a new student to our course by using the method insert(). This method is<br />
specific to this relationship type and creates a new student record. It also adds a record to the<br />
course_student table to link the course and the new student. Very handy!<br />
But, hold on. What's this new syntax?<br />
$course->students()->insert($new_student_information);<br />
Notice how we're not using $course->students->insert(). Our reference to students is<br />
a method reference rather than a property reference. That's because Eloquent handles methods<br />
that return relationship objects differently from other model methods.<br />
34