phplaraveliterationhas-manyilluminate-container

Illuminate - HasMany - Iteration



I am just doing my first exercises with Illuminate (Laravel) on my currently handmade database and website. I would like to improve by using MVC and found Illuminate interesting to use for the interaction with my database.

I worked the day on this bloody tiny code and can't find the problem and I hope someone out there has a good idea for me. Many thanks!

Basic question: Why can't I iterate over the courses to the given semester? While it is possible to call a specific course.

use Illuminate\Database\Eloquent\Model as Eloquent;

class Semester extends Eloquent {
    protected $table      = "tblSemester";
    protected $primaryKey = "SemesterID";

    public function getCourses() {
        // test if semester is correct
        echo $this->SemesterID, " - ", $this->Semestertext, "<br>"; 

        // This works fine and returns the expected result
        $course = $this->hasMany('Course', 'Semester')->first();
        echo $course->Number, " - ", $course->Title;

        // This doesn't work. It returns nothing. 
        // There seems to be no data in $courses (just metadata)
        $courses = $this->hasMany('Course', 'Semester');
        foreach ($courses as $course) {
            echo $course->Number, " - ", $course->Title;
            echo "<br>";
        }

        return "<h1>" . "Test ends" . "</h1>";
    }
}

Many thanks! Tim


Solution

  • First of all

    Since you said you are new to 'Laravel' and Want to follow MVC, I thought I may give you some advices.

    1. In laravel Models, don't include database manipulation codes. Instead write them in controllers.
    2. In Models, only include functions which belongs to a single models instance (non static functions).
      1. relationships
      2. query scopes
      3. accessors / modifiers

    Example Model

    class Semester extends Model 
    {
        protected $table = 'semesters';
    
        // relationships
        public function cources()
        {
            return $this->hasMany(Cource::class);
        }
    }
    

    Example Controller

    class SemesterController extends Controller
    {
        public function iterateOverCourcesOfGivenSemester()
        {
            // take first semester as an example.
            $givenSemester = Semester::first();
    
            // all the cources belongs to a given semester.
            $cources = $givenSemester->cources;
    
            foreach($cources as $cource) {
    
                // Warning! don't echo anything in a controller, Instead return them to a view.
                echo $course->Number, " - ", $course->Title;
                echo "<br>";
            }
        }
    }