Call to a member function media() on null
I have several related models. I have an "Event" model. Attached to this (via 1 to 1) is a Gallery model. Attached to that (via one to many) is a "Media" model. In the "created" observer for the Event, I'm trying to attach its gallery. I can create the gallery no problem, but when I then try and attach media to it I get the above error.
if ($model->gallery === null) {
$this->createGallery($model);
}
// product images or banner images
$file = Storage::put("public/event_images/", $image);
$file = str_replace("public/event_images/", "", $file);
$file = "/" . $file;
$model->gallery->media()->create([
"path" => $file,
"type" => "image"
]);
// The createGallery() function
private function createGallery($model)
{
$model->gallery()->create();
}
So I know to fix this, I have to "wait" until the gallery has been created before I try to access its relationships. But I can't figure out how to do this. This code works the second time it's run, suggesting that the gallery is indeed created - just not quickly enough before the code hits media().
PHP is a synchronous programming language, so it is impossible that you have to wait for something to complete.
The problem is that you loaded the relation already and this loaded relation won't re-validate until you load it again. which can be done using the load()
function.
Change your code to create the gallery like this:
if ($model->gallery === null) {
// Create the related model
$this->createGallery($model);
// Load the relation again
$model->load('gallery');
}