Home > database >  2 queries on the same model Laravel
2 queries on the same model Laravel

Time:09-27

i wanted to fetch all the rows from Course table whose userId is $userId . And from that list, i wanted to select the row which has the id field value as same as the inputted value $id. I tried the below one. It returns null. Any solutions?

$course=Course::where('userId',$userId)->pluck('id');
$data=$course->where('id',$id)->first();
dd($data);

CodePudding user response:

You shouldn't be using 'pluck' - that's just pulls out the specified column for matching records, and nothing else. Your $course collection (which is what's returned from your first line) is therefore just a collection containing IDs and nothing else.

You can chain multiple 'where' clauses together :

$course = Course::where('userID', $userID)->where('id', $id)->first();
dd($course);

CodePudding user response:

You can use the shorthand, which lets you pass in both search parameters in the where method.

$course = Course::where([
  'id' => $id,
  'userID' => $userID
])->first();
  • Related