Skip to content
Advertisement

Laravel eager loading phpunit testing

I am trying to do a GET request to retrieve a specific film via the id /GET 'film/{id}' etc

film_table

— id

— description

this is what is part of the response, what if I’ve many-to-many relationships within the film model as shown in the film model

JavaScript

is there a way you can include these tables as part of the response I came across something called eager loading in the Laravel docs but unsure if this covers what I need I have an example below but I’m lost if I’m on the right tracks?

FilmController

JavaScript

I am trying to write a PHPUnit test to ensure that when a film is grabbed via the id it returns the id, description as well as the options choosing from the many-to-many relations.

This is the test I’ve started

FilmControllerTest

JavaScript

can you include these relationships into a factory?

FilmFactory

JavaScript

LanguagesFactory

JavaScript

CategoriesFactory

JavaScript

Can i get some help with this please i’ve hit a brick wall some help and examples would be great 🙂 thanks!

Advertisement

Answer

You are very much on the right track. There are, however, some syntax errors.

This is how you grab a film, eager load required relationships and return it as JSON:

JavaScript

And this is how you test it:

JavaScript

Note that in your scenario you should have:

  • 3 model tables: films, categories, languages;
  • a factory for each model table;
  • 2 relationship tables: film_categories and film_languages.

Then you can either set relationships as part of your test using the attach method as in the example above, or you can use factory callbacks:

https://laravel.com/docs/6.x/database-testing#factory-callbacks

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement