When I try the firstOrCreate()
on a relationship of another model, it does not work:
Client::find($id)->users()->firstOrCreate(array('email' => $email));
This returns an error saying
Call to undefined method Illuminate\Database\Query\Builder::firstOrCreate()
Running this directly on the model User
will work though.
This is correct, the users() function does not return a (new, empty or created) User model, it returns a collection object.
You are misinterpreting that document. The relationship object has a create() method and a save() method, however the relationship object is not a full model object. To get all of the functionality of a full User model object (such as firstOrCreate()) then you have to call them on the model object.
So, for example, this code should work:
Note that it should be OK to save the $user object here directly from the Client model's relationship, even though it may already exist here, it should just update the client_id field on the $user object when you do so.