I'm new to Laravel and wanted to know if I can solve my problem without being in pure PHP, that is, using Laravel's own resources. Here's the current situation and what I want to do:
I have a table named Departments, where I include the department name (column name) and 1 focal point (column puntofocal_id), 1 manager (column manager_id) and 1 or more backups (column backup). When saving the record I save the IDs of the PontoFocal, backups and managers that I get from the Users table. Until then, I use in my App / Department file the hasOne for the users table and I can pull the user name by the ID entered in the Departments table.
public function pontofocal(){
return $this->hasOne(Usuario::Class, 'id', 'pontofocal_id');
}
public function gestor(){
return $this->hasOne(Usuario::Class, 'id', 'gestor_id');
}
public function backups(){
return $this->hasOne(Usuario::Class, 'id', 'backup');
}
However the Backup column I can save more than one ID in the same record. I separate them by comma.
In my list.blade.php I used a foreach inside the other foreach to get the value of the backup field (example: 1,4,5) to transform into an array containing the IDS 1, 4 and 5, using an explode and returns this information for the variable $ department-> backup, in order to use the relationship and get the name field of the users table as described below:
@foreach($departamentos as $departamento)
<tr>
<td>{{ $departamento->nome }}</td>
<td>{{ $departamento->gestor->name }}</td>
<td>{{ $departamento->pontofocal->name }}</td>
@php
$arraybackups = explode(",",$departamento->backup);
@endphp
<td>
@foreach($arraybackups as $arraybackup)
@php
$departamento->backup = $arraybackup;
@endphp
{{ $departamento->backups->name }}
@endforeach
</td>
At first it works but it seems like it takes the value of the name field only from the first ID and repeats to the others even though they are different IDs. As below:
WhengivinganechotoseeifIamwritingthecorrectIDsextractedfromthearray,Iseethatyes,theyarecorrectasbelow.seethattheyaredifferentIDs,butitalwaysbringsmethesamenameasthefirstIDoftheline:
Is there any way to do this that I want?
Thank you!