Skip to content

Instantly share code, notes, and snippets.

Avatar
🏡
Working from home

Timothy de Jongh IceTimux

🏡
Working from home
View GitHub Profile
View zr64t.md

~Laravel | On accessors with the same name as the database field


If you have $product->price and you want to format it, do not create the accessor function getPriceAttribute() on your model. Why?

Consider this example.

I have a OneToMany relation between Event and Major models as events belongsTo Major and Major hasMany events.

View aia5k.md

~PHPUnit | assertTrue() vs. assertEquals()


When using assertTrue() with some condition, the error message is often not useful. In this case it is better to use assertEquals() or similair that produces more meaningful output.

Consider the following example.

// if this test fails...
View e19v7.md

~Programming | Replacing switch statements with lookup tables


consider the follwoing switch statement. It translates a color string from english to Papiamentu.

def color_mapper(color)
  case color
  when 'yellow'
View wt8h7.md

~Laravel | Route Model Binding, bind to field other than id


When doing Route Model Binding, you can bind to another field other than id by specifying :field like slug, in case of SEO-friendly URLs.

Consider the following example.

// routes/web.php
View 9k007.md

~Laravel | Check if URL contains string


Often times you want to check if the URL contains a certain string for example the substring admin/ inside https://yourapp.com/admin/settings

A convenient way in Laravel is to use the is method.

  if  ($request->is('admin/*')) {
View 51hxg.md

~Travis CI ~Ruby | Ruby example .travis.yml


---
language: ruby
cache: bundler
rvm:
  - 2.7.0
View k64v2.md

~Laravel | Keep Eloquent queries DRY by using Local Scopes


Consider the following example.

// posted withtin 14 days
$recentPosts = Post::where('created_at', '>', now()->subDays(14))
  ->latest()->take(10)->get();
View d1467.md

~Programming ~Patterns | The Command pattern


Take a function that performs some opereation and encapsulate it into its own Class.

Take this function here for example.

def save_invoice(invoice)
View 3f995.md

~Laravel ~Fix | How to fix Call to a member function connection() on null error on Laravel >=6.x


I decided to spin up a fresh Laravel 8 installation to do some practicing on. I noticed that if you run php artisan test all tests pass out of the box. This is a little strange to me, I feel that you should start with a failing test. So I decided to go into the example unit test and modify it so it will NOT PASS!

My idea was simple, I am going to pull in the User model and assert that there should be 1 user there. This test should not pass. I did however run the migrations.