Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rjruiz's avatar

relaciones con el ORM ELOQUENT

friends I am trying to apply eloquent my query basically I have 3 tables of which clients and companies users already have my query which works perfect but now I want to apply eloquent to simplify things this is my original query

public function index()
    {
        $clientes = Client::join('users','clients.id','=','users.id')
        ->join('companies', 'users.id','=','companies.id')
        ->select('users.id','companies.registro_fiscal','companies.nombre',
            'companies.telefono','companies.sitio_web','clients.direccion',
            'clients.ciudad','clients.provincia','clients.pais','users.name','clients.telefono_contacto','users.email')
        ->orderBy('users.id','desc')->paginate(5);;       
     
        return view('clientes.index', compact('clientes'));
    }

Estas son mis relaciones

user model

public function client()
    {
        return $this->hasOne(Client::class);
    }

client model

public function company()
    {
         return $this->belongsTo(Company::class);
    }

public function user()
    {
        return $this->hasOne(User::class);
    }

model company

public function client()
    {
        return $this->hasOne(Client::class);
    }

These are my relationships would help me a lot by giving me some example where more than one table is related to then make the query in the controller as is my case thanks for your help friend

0 likes
1 reply
aurawindsurfing's avatar

Hey @rjruiz

    public function index()
    {
        $clientes = Client::with('user', 'company')->orderBy('users.id','desc')->paginate(5);
        
        return view('clientes.index', compact('clientes'));
    }

not sure about orderBy, try without it first.

1 like

Please or to participate in this conversation.