Laravel Eloquent pass variable to with relationship function
18,688
Solution 1
Use use
in the closure
->with(['assignment' => function ($query) use ($date){
Solution 2
You can try the following:
$user = User::with(array('relationShipMethod' => function($query) use ($request) {
$query->wherePivot('column', $request->column);
}))->first();
relationShipMethod = method with you relationship another table for example users has posts maybe relationShipMethod could be posts method
Author by
Ricki Moore
Updated on July 24, 2022Comments
-
Ricki Moore almost 2 years
I am using eloquent to make a query for a database entry and it's corresponding relationship. The problem is I need to pass the
$date
variable into the relationshipquery
like shown below:I can pass the
$date
variable to the first query because its not inside a with function. How can I achieve this with the second?Query
public static function find_task($type, $date) { if($type == 'student') { $mySid = Student::student_id(); $allTasks = TaskAssignment::where('student_id', $mySid) ->with('task') ->where('dueDate', $date) ->orderBy('dueDate', 'asc') ->get(); } elseif($type == 'teacher') { $myTid = Teacher::teacher_id(); $allTasks = Tasks::where('teacher_id', $myTid) ->with(['assignment' => function ($query) { $query->where('dueDate', $date); $query->orderBy('dueDate', 'asc'); }])->get(); } else { return 'error this page does not exist'; } return $allTasks; }