Posts List

Eloquent Eager Loading Constrained by Pivot

How to use Laravel's Eloquent ORM to constrain eager loading of relations using `with()` and `wherePivot()`

Computing Eloquent Model Deltas

Computing the differences or deltas between Eloquent models is a common task in many data oriented apps. The easiest way that I have found out how to do so is below: // This is assumed to be in \App\YourModel /** * @param \App\YourModel $model * * @return array */ public function delta(\App\YourModel $model) { // array_diff() is an easy way to produce deltas $baseline = $model->attributesToArray(); $possiblyChanged = $this->attributesToArray(); /* * $baseline = ['test' => 500, 'not_changed' => 5] * $possiblyChanged = ['test' => 700, 'not_changed' => 5] */ /* * $delta == ['test' => 700] */ $delta = array_diff($possiblyChanged, $baseline); // Here I unset possible changes that I don't care about unset($delta['id']); unset($delta['created_at']); unset($delta['updated_at']); return $delta; }

Eloquent Model JSON Serialization and Deserialization

Awhile back I needed to save an Eloquent model to the DB so that I might compute a delta later on. Json serves this purpose nicely since the json data type is now natively supported in many languages. One could do this manually but, fortunately, Laravel makes this easy on us. We can utilize model mutators to dynamically convert the input and output of a specific database column. For example, say we want to save a passed in model as json and that the column that we want to save to is called json:

Laravel seeding using a yield generator


How to create Eloquent models from Laravel Query Builder results

Sometimes Eloquent doesn’t provide all of the functionality and access to data that you need out of the box. Even Taylor Otwell, the framework’s creator, often uses query builder for his DB operations. Getting wet Refer to the the query builder docs on how to use it: Query Builder Running a query such as: \DB::table('users')->take(2)->get(); will return an array of stdClass objects. What if you want to change those into User model objects?