A.B.Developer A.B.Developer - 1 year ago 69
PHP Question

eager load of relations of a specific model in laravel

I have a model named

like this:

class Test extends Model
public $primaryKey = 'test_id';
public function questions ()
return $this->belongsToMany('App\Question', 'question_test', 'test_id', 'question_id');

And a
model like this:

class Question extends Model
public function tests ()
return $this->belongsToMany('App\Test', 'question_test', 'question_id', 'test_id');

As you see there is a
relation between this two model.

Now in a controller function, I want to get an specific Test(by id) and send it to a view. then eager load all it's
related models and send it to another view. like this :

public function beginTest ($course_id, $lesson_id, $test_id)

$test = Test::find($test_id);

if ($test->onebyone) {

return view('main/pages/test/test-onebyone', compact('test'));

} else {

$test = $test->with('questions.options')->get();
return view('main/pages/test/test-onepage', compact('test', 'done_test_id'));


Problem is that when I use
laravel method to eager load relations, it return all Test models with their
relations while I want to get relations of selected
model only.

what is your solution to solve that?

Answer Source

You can use 'lazy eager loading'.


Using with off the model instance will make it use a new builder and cause a new query to be executed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download