arraygod's avatar

firstOrCreate parent, then create child, possible?

Having issues for some reason creating two models inside a model. Child and parent through/inside hasOne. Perhaps thats the reason? Though Ive tried in Tinkerwell, as well. Ive tried several other ways. Works only if Parent model has been created (dispute), or exists().

Model Method: public function newDispute(string $message) {

if(is_null($this->dispute)) {
        $newCase = Dispute::Create(['ref_id' => $this->id]);
            if($newCase->id) {
                //$this->dispute->refersh(); 
                $newMessage = new DisputeMessage;
                $newMessage->message = $message;
                $newMessage->setDispute($this->dispute); 
                $newMessage->setAuthor($this->customer);
            }
    }  elseif($this->dispute->exists())  {
        $newMessage = new DisputeMessage;
        $newMessage->message = $message;
        $newMessage->setDispute($this->dispute); 
        $newMessage->setAuthor($this->customer);
    }

}

Tinker Method:

Dispute::firstOrCreate(["ref_id" => 25]) ->messages() ->create([ "message" => 'test', "author_id" => 1 ]);

or

Shipped::latest()->first()->newDispute('Did not recieve item');

Strange I feel like this has never been an issue. Any ideas? Laravel Framework 10.42.0 php 8.2

0 likes
1 reply
tykus's avatar
tykus
Best Answer
Level 104

You already established that $this->dispute is null, so you need to use the $newCase here:

if(is_null($this->dispute)) {
    $newCase = Dispute::Create(['ref_id' => $this->id]);
    // ... 
    $newMessage->setDispute($newCase); 
} elseif ( // etc
1 like

Please or to participate in this conversation.