Skip to content

Instantly share code, notes, and snippets.

Working from home

Timothy de Jongh IceTimux

Working from home
View GitHub Profile

~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.


~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

~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

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

  if  ($request->is('admin/*')) {

~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...

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

language: ruby
cache: bundler
  - 2.7.0

~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'

~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))

~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)

~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.