It’s very hard to get the meaning of your code, because it’s written in quite an unstructured manner, and the variable names don’t make things any easier.
$this->receiver = new Receiver();
$this->receiver = $receiverData;
Here you set $this->receiver to a blank model, then immediately overwrite it to whatever $receiverData is (going by your dd() output, probably an array).
if ($reversed) {
$receiver = Receiver::find($receiverData['id']);
$new_receiver = $receiver->replicate();
$this->receiver = $new_receiver;
} else {
$this->receiver->user_id = $receiverData->user_id = auth()->id();
}
Here, depending on $reversed, you either:
- overwrite
$this->receiver again, this time to a model that replicates a model you load from the database based on the array $receiverData
- or set the user ID property on
$this->receiver to the user ID on the object $receiverData, which you set to the current user’s ID
None of that makes any sense at all.
In one branch of the if statement, you treat $receiverData as an array; in the other, you treat it as an object. It cannot be both.
In one branch, you’re creating a whole model and replicating it, then saving that model in $this->receiver. In the other, you leave $this->receiver as it is (the contents of $receiverData) and just update a single property.
In one branch, you set the user ID property to be the current user’s ID; in the other, you don’t set it at all (so you’re counting on it being present in $receiverData, I guess?).
Nowhere do you check what $receiverData actually is – if this is data you’re getting from user input, it needs to be validated before you start saving it into models.
From your code, it’s impossible to work out what exactly $receiverData is supposed to be, but I’m going to guess that it’s an array of data (not a model) that may or may not be used to create a new model instance, based on the mysteriously named boolean(?) called $reverse. I have no idea what $reverse is supposed to represent, but for its purpose, I’m going to guess that if it’s true, the receiver should be a replica of an existing model; if it’s false, it should be a new model created from the data in $receiverData.
I’m also going to guess that you want to set the user ID to the current user regardless of the value of $reverse.
Assuming those guesses are accurate, this will suffice:
// If $receiverData is from user input, make sure to validate it first here
$this->receiver = ($reversed) ?
Receiver::findOrFail($receiverData['id'])->replicate() :
$this->receiver = new Receiver($receiverData)
;
$this->receiver->user_id = auth()->id();
$this->receiver->save();
I’ve used ->findOrFail() instead of ->find() so that the function will throw an exception if there is no existing record matching $receiverData['id'].