Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent pass variable to with relationship function

Tags:

php

mysql

laravel

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 relationship query 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;
}
like image 956
Ricki Moore Avatar asked Apr 04 '16 20:04

Ricki Moore


2 Answers

Use use in the closure

->with(['assignment' => function ($query) use ($date){
like image 81
Muihlinn Avatar answered Nov 19 '22 09:11

Muihlinn


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

like image 36
edocollado Avatar answered Nov 19 '22 09:11

edocollado