Search code examples
phplaravelmodellaravel-8laravel-blade

Attempt to read property "episode" on null


The following code snippet is to collect and display the number of times of several videos. But it shows the following error:

Attempt to read property "episode" on null

from this line:

$course->time = $this->getCourseTime($course->episode->pluck('time'));

AdminController:

public function setCourseTime($episode)
{
    $course = $episode->course;
    $course->time = $this->getCourseTime($course->episode->pluck('time'));
    $course->save();
}


protected function getCourseTime($times)
{
    $timestamp = Carbon::parse('00:00:00');
    foreach ($times as $row)
    {
        $time = strlen($row) == 5 ? strtotime('00:' . $row) : strtotime($row);
        $timestamp->addSecond($time);
    }

    return $timestamp->format('H:i:s');
}

Model Course.php

public function episode()
{
    return $this->hasMany(Episode::class);
}

Model Episode.php

public function courses()
{
    return $this->belongsTo(Course::class);
}

EpisodeController.php

public function store(EpisodeRequest $request)
{

    $episode = Episode::create($request->all());
    $this->setCourseTime($episode);

    return to_route('episode.index');
}

Solution

  • I would assume on the Episode Model you mean to name the relationship course not courses, since it is a Belongs To (singular) relationship.

    Currently, unless you have an attribute/accessor/relationship named course you will be getting back a null when trying to access that 'attribute'/property.

    Additionally, when creating a new Episode model it isn't going to create the related record for you. After creation the related record doesn't exist so the relationship would not return a result.