Laravel - firstOrCreate() calls relation method

Joined
Jun 23, 2010
Messages
2,618
Reaction score
2,232
Hello,

So I have a simple class which throws an exception "Trying to get property of non-object". After a few minutes of debugging I found the source of it. The lines provided below causes the exception.

Code:
$dbitem = Item::[COLOR=#00ffff]firstOrCreate[/COLOR](array(
    'type_id' => 1,
    'filename' => $xml_filename
));

I wrapped that arround a try/catch case to get a detailed exception log. When done that, it seems the firstOrCreate method calls a relationship method in the model.

Code:
public function item()
{
    $model = ucfirst($this->[COLOR=#0000ff]type[/COLOR]->value); // Throws the exception
    
    return $this->hasOne($model);
}

public function [COLOR=#0000ff]type[/COLOR]()
{
    [COLOR=#008000]return $this->belongsTo('Type');[/COLOR]
}

Because I want the first row it finds and if not create it. The `type_id` field when creating a new record is empty which causes to return NULL. by the type relationship.

Anyone any idea why it calls the relationship on that method and what the solution is to solve my problem.


Thank you,
- Joopie​



Solved: the method "item" already exist in the parent class. Renamed it and working fine now!
 
Last edited:
Back