Eloquent Whisperer — Laravel

Whisper Eloquent queries: 15 levels of where, with, has and eager loading. The most effective Laravel ORM game for mastering model relationships.

What you learn in this game

One model class stands for one table, and a static method on that class starts a query. Warga::first() takes the first card only, Warga::count() counts the cards. A result holding many models comes as a Collection. In the archive room of the District Office, Ms. Puspa whispers your request in PHP and the cards are pulled from the cabinet to the table. The back of each drawer only opens when a whisper is pulled for real.

The id column is the primary key: no other card uses a card's number. Warga::find(3) looks for the card numbered 3 and returns that model itself, not a Collection, or null when there is none.

where filters rows with a column, an operator and a value: Warga::where('lahir', '<', 1970) sets up a filter for villagers born before 1970. The filter only runs when the whisper ends with get().

A table can be read without a model too: DB::table('warga') starts a query builder for that table, and its get() gives stdClass rows. select picks the columns brought: DB::table('warga')->select('nama', 'rt')->get() brings just the names and neighbourhoods.

orderBy('column', 'desc') sorts from the largest; with no second argument the order goes up. Several orderBy calls are used in turn: the second only decides rows that tie on the first. Dagangan::orderBy('warga_id')->orderBy('nama')->get() sorts the wares by seller, then by the ware's name within each seller.

The middle argument of where can be >, >=, <, <= or !=. take(n) (or limit(n)) caps the number of rows, and usually comes with an orderBy so the rows taken really are the top ones: Dagangan::orderBy('harga')->take(2)->get() takes the two cheapest wares.