Trucks tips

Always Check Idle Hours

Don't retract your mirrors if it's going to snow / freezing rain. I have a 2014 Laramie and couldn't get the electric mirrors to extend today in 7degF weather. Had to chip off ice from around the mountings before they would work.

orWhere with multiple parameters

Finally, you can pass an array of parameters to orWhere(). “Usual” way:

1$q->where('a', 1);2$q->orWhere('b', 2);3$q->orWhere('c', 3);

You can do it like this:

1$q->where('a', 1);2$q->orWhere(['b' => 2, 'c' => 3]);

Transform brackets into an Eloquent query

What if you have and-or mix in your SQL query, like this:

1... WHERE (gender = 'Male' and age >= 18) or (gender = 'Female' and age >= 65)

How to translate it into Eloquent? This is the wrong way:

1$q->where('gender', 'Male');2$q->orWhere('age', '>=', 18);3$q->where('gender', 'Female');4$q->orWhere('age', '>=', 65);

The order will be incorrect. The right way is a little more complicated, using closure functions as sub-queries:

1$q->where(function ($query) {2    $query->where('gender', 'Male')3        ->where('age', '>=', 18);4})->orWhere(function($query) {5    $query->where('gender', 'Female')6        ->where('age', '>=', 65);7})

What is the result of an update()?

Have you ever wondered what this code actually returns?

1$result = $products->whereNull('category_id')->update(['category_id' => 2]);

I mean, the update is performed in the database, but what would that $result contain? The answer is affected rows. So if you need to check how many rows were affected, you don’t need to call anything else – update() method will return this number for you.

Override updated_at when saving

Did you know that ->save() method can accept parameters? As a result, we can tell it to “ignore” updated_at default functionality to be filled with current timestamp. See this:

1$product = Product::find($id);2$product->updated_at = '2019-01-01 10:00:00';3$product->save(['timestamps' => false]);

Here we’re overriding default updated_at with our pre-defined one.

Create additional things when creating a model

We all know this Artisan command:

1php artisan make:model Company

But did you know there are three useful flags to generate related files to the model?

1php artisan make:model Company -mcr
  • -m will create a migration file
  • -c will create a controller
  • -r will indicate that controller should be resourceful

Chunk() method for big tables

Not exactly Eloquent related, it’s more about Collection, but still powerful – to process bigger datasets, you can chunk them into pieces. Instead of:

1$users = User::all();2foreach ($users as $user) {3    // ...

You can do:

1User::chunk(100, function ($users) {2    foreach ($users as $user) {3        // ...4    }5});