I need to create an order system for the staff of a company, each user has one or more employees associated with it. Within the orders, the employees associated with the user must be shown.
The problem is that when it shows me the data, it does not bring me any employee.
The order controller:
public function create()
{
$users = User::all();
$empleados = Auth::user()->empleados;
$productos = Producto::all();
return view('pedido.create', compact('empleados','productos', 'users'));
}
The order view:
<input id="id_usuario" name="id_usuario" type="text" class="form-control" value="{{auth()->user()->name}}" readonly>
<div>
<label for="" class="form-label">Empleado:<p></label>
<select name="id_empleado" class="form-control">
<option value="">-- Seleccione el empleado -- </option>
@foreach ($empleados as $empleado)
<option value="{{ $empleado->id }}">{{ $empleado->nombre }}</option>
@endforeach
</select>
Model used:
class Empleado extends Model
{
use HasFactory;
protected $fillable = ['nombre', 'id_user', 'cargo', 'departamento', 'empresa'];
public function users(){
return $this->belongsTo(User::class, 'id_user', 'id');
}
public function pedidos(){
return $this->hasMany(Pedido::class, 'id', 'id_empleado');
}
}
User model:
class User extends Authenticatable
{
public function empleados(){
return $this->hasMany(Empleado::class, 'id', 'id_user');
}
}
There is a logic error which we are going to solve step by step, first modify the following
$empleados = Empleado::where('id_user',Auth::user()->id);
With these we are consulting the Employees table and we are telling it to bring all the results of the id_user field that match the id of the active user EDIT The method needs to be added
->get()
to the query to obtain all the required results, leaving$empleados = Empleado::where('id_user',Auth::user()->id)->get();