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

mecjos's avatar

Gettin Data from Several Models

Hi. I am new on Laravel and confused a bit. I have simple db relationship but I couldn't make it with ORM. I have three tables - users, customers, customers_detail and images. customers table has one to one relation with customers_detail and customers_detail table has one to many polymorphic relation with images table. I want to get customer detail table and image from customer model. How can I do this? I can't reach customer_detail model's method from inside cutomer model.. I hope I could explain ) thank you..

0 likes
2 replies
lostdreamer_nl's avatar
Level 53

User

public function customer()
{
    return $this->hasOne(Customer::class);
}

Customer

public function user()
{
    return $this->belongsTo(User::class);
}
public function detail()
{
    return $this->hasOne(CustomersDetail::class);
}
public function images()
{
    return $this->morphToMany(Image::class, 'imagable');
}

customers table has a user_id

CustomersDetail

public function customer()
{
    return $this->belongsTo(Customer::class);
}

customers_detail table has a customer_id

Image

public function customer()
{
    return $this->morphedByMany(Customer::class, 'imagable');
}

images has 2 tables: images: id, name, filename ? imagables image_id, imagable_type, imagable_id

$userData = User::with('customer.detail', 'customer.images')->find(1);

Will give you user 1, with it's customer object, it's details, and images.

For the DB : read https://laravel.com/docs/5.5/eloquent-relationships as well.

Please or to participate in this conversation.