Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Daniel-Pablo's avatar

create a record with hasMany

Hi, am new on this, I notice that I can create a record with hasOne

$user->wallet->addPin(); // this will call a function to run that function in the MODEL

I want to do the same but the new relation ship is HASMANY

so when I call it the laravel pops this message

Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::createInvoice()
 // WHY GET THIS?

So I understand that I cant call the function

return $user->invoice->createInvoice();

because return that error, HOW CAN I DO IT??? IS THERE A WAY TO CALL THE FUNCTION OF THE MODEL??

I have to do this on the controller, but I want to do it on the model HOW??

       $user->invoices()->create([
             'service_id' => $orderId->service_id,
             'review' => $request->review,
             'stars' => $request->stars,
         ]);
0 likes
4 replies
wheesnoza's avatar

Maybe you could try something like this.

// User model

public function createInvoice(array $attributes)
{
    $this->invoices()->create($attributes);
}

And call this using user model instance.

$user->createInvoice([
   'service_id' => $orderId->service_id,
   'review' => $request->review,
   'stars' => $request->stars,
]);

$user->invoice()return a HasMany class instance and not an instance of Invoice model because is a has many relationship.

I hope it helps you

nolros's avatar

You can do this

return $user->invoice()->create([...]);


// this is accessing the invoice data on the relationship
$user->invoice

/// this is the invoice model and as such you can run the model method
$user->invoice()

Daniel-Pablo's avatar

please, i want to create this

        $user->invoices()->create([
             'payment' => $request->delinnsAmount,
             'reference' => 'Charge Account',
             'charge' => 1
         ]);

but inside a function inside the MODEL nothing else, i don't want to call this inside a controller, inside the controller i want to send the parameters

Daniel-Pablo's avatar
Daniel-Pablo
OP
Best Answer
Level 12

figure it out

public function createInvoice($userID , $usd , $reference , $charge  ){

  $invoice = new invoice;
  $invoice->user_id = $userID;
  $invoice->payment = $usd;
  $invoice->reference = $reference;
  $invoice->charge = $charge;
  $invoice->save();

}

in the model

then call it

Invoice::createInvoice( $user->id , $amount , 'Charge Account' , 1);

but I did not like that way because i got to make the relation ship between the user->id and I prefer with the relation ships

Please or to participate in this conversation.