## Posts List

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; }

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:

I was needing to improve the performance of a pivot table seeder recently and decided to use a generator to do it. Interestingly, one of the easiest to implement iterators is the yield syntax introduced in PHP 5.5. It allows for good abstraction between the data that is to be iterated and the source of said data. That can lead to significant performance increases as well since it might, depending on the use case, reduce database calls or the amount of data being stored in memory among other things.

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?