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

raviawasti's avatar

How can i get 3 table data in index in laravel?

I have 3 tables schools, school_Details,ratings

** Schools table**

id

name

phone

school

email

status

School details table:

-id

school_id

image

status

ratings table:

-id

school_id

rating_value

status

both rating &school details have only one row for one school_id.

Now how can i get all details from all 3 tables in index from schoolController

0 likes
2 replies
Tray2's avatar

I would probably use a database view for this.

CREATE VIEW  school_views AS
SELECT s.name, 
              s.phone,
              sd.image,
              r.rating_value,
              r.status
FROM schools s,
            school_details sd,
            ratings r
WHERE s.id = sd.school_id
AND s.id = r.school_id

Then I'd create an Model for it and then in the controller I do

$schools = SchoolView::all();
return view('schools.index', compact('schools'));

That way I don't need to create any complicated eloquent query. Put the view creation in a migration file.

In yourup()

DB::statement("CREATE VIEW  school_views AS
SELECT s.name, 
              s.phone,
              sd.image,
              r.rating_value,
              r.status
FROM schools s,
            school_details sd,
            ratings r
WHERE s.id = sd.school_id
AND s.id = r.school_id");

and in your down()

DB::statement('DROP VIEW school_views');

However in your case I'd put all the fields in one table since they are one to one relationships. I'm not saying you always should put one to one in the same table but in this case I would at least for starters.

Snapey's avatar

There's nothing complicated about this. Just create relationship from School to Detail model and Rating model

In the controller you can then eager load

School::with('detail','rating')->find(1)

and then access the attributes as nested models, eg

$school->rating->rating_value

Please or to participate in this conversation.