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

jhutto's avatar

Query that has a where clause and with clause.

I'm writing a ajax call to a controller with a function to return $courses I have two tables/Models... Courses and Instructors.

Instructor has...

public function Courses()
    {
        return $this->hasMany('App\Course');
    }

Courses has...
public function Instructor()
    {
        return $this->belongsTo('App\Instructor');
    }

I have a query that's working but would like to know how to write it the eloquent way...

This works. $courses = \App\Course::where('SemesterID', $id)->join('Instructors', 'somascourses.Instructor_id', '=', 'Instructors.id')->get();

This gives me an error not understanding the ::with..... //$courses = \App\Course::where('SemesterID', $id)::with('Instructor')->get();

Sorry... A couple of more questions.

  1. Should I be writing these as functions in the Model ? Or is it ok in the controller?

  2. How do I bring over only specific fields from the instructors table in the query?

0 likes
6 replies
shez1983's avatar

$courses = \App\Course::where('SemesterID', $id)::with('Instructor')->get();

only the first :: works from then on you have to use ->

jhutto's avatar

Got it.. Thanks... $courses = \App\Course::where('SemesterID', $id)->with('Instructor')->get(); This worked.

What about the other two questions???

Snapey's avatar

rewrite the relationship

public function Instructor()
{
        return $this->belongsTo('App\Instructor');
}

to

public function instructor()
{
        return $this->belongsTo('App\Instructor');
}

then the eloquent way is;

$courses = \App\Course::with('instructor')
            ->where('SemesterID', $id)
            ->get();

now, instead of being additional attributes of course, the instructor is a child model

eg. {{ $course->instructor->name }}

ksparkar's avatar

There are no 'rules' about where you should be putting the functions. Personally, if it is just a single line of code then putting in the Controller is ok. Anything more and I would start considering extracting.

To get specific columns do this: \App\Course::where('SemesterID', $id)::with('Instructor:column1,column2')->get();

jhutto's avatar

Well .. I tried all of these but here's what worked..

$courses = \App\Course::where('SemesterID', $id)->join('Instructors', 'somascourses.Instructor_id', '=', 'Instructors.id')->get();

It returns all the fields from instructors table. I could not get any of the others to work and return the fields. I would love to be able to only return a few of the fields. Anyone????

Snapey's avatar

Eloquent relationships are probably not working for you since you don't follow convention for key names, and have not specified the columns to use in the relationship.

Please or to participate in this conversation.