npm install: ERR_SSL_CIPHER_OPERATION_FAILED and ERR_SSL_CIPHER_OPERATION_FAILED

I got these errors after trying to run npm install.

# npm install

...
npm ERR! gyp ERR! UNCAUGHT EXCEPTION
npm ERR! gyp ERR! stack TypeError: Cannot assign to read only property 'cflags' of object '#<Object>'
npm ERR! gyp ERR! stack     at createConfigFile (/app/node_modules/node-gyp/lib/configure.js:117:21)
npm ERR! gyp ERR! stack     at /app/node_modules/node-gyp/lib/configure.js:84:9
npm ERR! gyp ERR! stack     at FSReqCallback.oncomplete (node:fs:191:23)
npm ERR! gyp ERR! System Linux 6.6.12-linuxkit
npm ERR! gyp ERR! command "/usr/local/bin/node" "/app/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
npm ERR! gyp ERR! cwd /app/node_modules/node-sass
npm ERR! gyp ERR! node -v v20.11.1
npm ERR! gyp ERR! node-gyp -v v7.1.2
npm ERR! gyp ERR! Node-gyp failed to build your package.
npm ERR! gyp ERR! Try to update npm and/or node-gyp and if it does not help file an issue with the package author.
npm ERR! Build failed with error code: 7

I did the following to fix these

  • installed system packages
  • updated node to the current version (not LTS)
  • update npm to the latest version
  • update node_gyp to the latest version
  • updated all versions in package.json to the latest versions
  • removed package-lock.json file
  • removed node_modules directory
  • cleaned npm cache
  • ran npm install again

I installed the following packages:

# apt-get update && apt-get install -y ca-certificates curl gnupg zip unzip git software-properties-common rsyslog

Upgraded node, npm, node_gyp and cleared cache

 # npm cache clean -f \
  && npm install -g n \
  && n current
# npm install -g npm@latest
# npm update -g node-gyp
# rm -rf node_modules package-lock.json

Then, update all package versions in package.json to their latest version.

And then tried again, this time it worked.

# npm install

Did this work for you as well? Had to do less? More? Let me know and I’ll update this post.

Add pint to PHPStorm File Watchers

Open your settings in PHPStorm and go to Tools > File Watchers

Add a new Custom File Watcher and use the following information:

Name: pint
File type: PHP
Program: $ProjectFileDir$/vendor/bin/pint
Arguments: $FileRelativePath$
Output paths to refresh: $FileRelativePath$
Working directory: $ProjectFileDir$

Add url to your laravel Exception context

props to @_newtonjob https://twitter.com/_newtonjob/status/1724023158787694864/photo/1

<?php
// file app/Exceptions/Handler.php
class Handler extends ExceptionHandler
{
   
    public function register(): void
    {
       
       //
    }

    public function context()
    {
        return array_merge(parent::context(), [
            'url' => url()->full(),
            'method' => request()->getMethod(),
        ]);
    }
}

Show your query with values in Laravel 10 Eloquent

When debugging your eloquent model queries, it’s often nice to know which SQL query is executed in the end.

By default, Laravel won’t show you the values used in the query. Instead, it shows you a questionmark ? instead of the actual values. This is because of the parameter bindings in PDO.

Let’s create a ->toSqlWithBindings() macro so you can have the full query.

Create the macro as ServiceProvider

<?php

// file app/Providers/MacroServiceProvder.php

declare(strict_types=1);

namespace App\Providers;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;

class MacroServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        Builder::macro('toSqlWithBindings', function () {
            /** @var Builder $this */
            $bindings = array_map(
                fn ($parameter) => (is_string($parameter) || $parameter instanceof Carbon) ? "'{$parameter}'" : $parameter,
                /** @var Builder $this */
                $this->getBindings()
            );

            return Str::replaceArray(
                '?',
                $bindings,
                $this->toSql()
            );
        });

        /** @var Builder $this */
        EloquentBuilder::macro('toSqlWithBindings', fn () => $this->toBase()->toSqlWithBindings());
    }
}


the serviceprovider file containing the macro which gives us the toSqlWithBindings() method on eloquent queries

Use it

Change field to enum in Laravel 10

In this post I will show you how to change an existing field in your Laravel application to change to enum.

I have a field status which was kept in line by having class constants defining the value for this field. But I really missed the database keeping the value in line though.

Changing the class constants to a PHP 8 enum and changing the database field to enum had some caveats so if you want to change your datatype to enum as well, follow along.

Change the class constants to an enum

I use the trait EnumEnhancements for the enum as this provides very handy helper methods:

ImportStatus::valueArray(): an array with the values of the enum
ImportStatus::valueList(): a string with the values of the enum: ‘pending, validating, importing, …’

<?php

declare(strict_types=1);

namespace App\Models\Enums;

use Othyn\PhpEnumEnhancements\Traits\EnumEnhancements;

enum ImportStatus: string
{
    use EnumEnhancements;

    case PENDING = 'pending';
    case VALIDATING = 'validating';
    case VALIDATION_FAILED = 'validation_failed';
    case VALIDATED = 'validated';
    case CREATING_IMPORT_JOBS = 'creating_import_jobs';
    case IMPORT_JOBS_CREATED = 'import_jobs_created';
    case IMPORTING = 'importing';
    case IMPORTED = 'imported';
    case FAILED = 'failed';
    case CANCELLED = 'cancelled';
    case FINISHED = 'finished';
}

Create a Laravel migration to change the field to an enum

NOTE: changing an existing field to an enum in your database requires you to do this with a DB statement. You cannot use a query builder for this or you’ll get the following error :

Unknown column type "enum" requested. Any Doctrine type that you use has to be registered with \Doctrine\DBAL\Types\Type::addType(). You can get a list of all the known types with \Doctrine\DBAL\Types\Type::getTypesMap(). If this error occurs during database introspection then you might have forgotten to register all database types for a Doctrine Type. Use AbstractPlatform#registerDoctrineTypeMapping() or have your custom types implement Type#getMappedDatabaseTypes(). If the type name is empty you might have a problem with the cache or forgot some mapping information.

I change the existing column from a string to an enum in 4 steps:

  1. Get the current status of each record so it won’t get lost in the following steps
  2. Set all current values to NULL so that changing the datatype of the field won’t cause trouble with existing values
  3. Do the actual changing of the datatype of the field to enum
  4. Change all statuses back to their original value but act on cases where the existing value is not valid with the current enum values

<?php

declare(strict_types=1);

use App\Models\Enums\ImportStatus;
use App\Models\ImportFile;
use Illuminate\Database\Migrations\Migration;

return new class () extends Migration {
    public function up(): void
    {
        // 1. Get the current status for each row
        $importFiles = DB::table('posts')->get(['id', 'status']);

        // 2. Set all statuses to NULL
        DB::table('posts')->update(['status' => null]);

        // 3. Change the column to an enum
        $this->changeStatusToEnum();

        // 4. Set the status for each row to the value we got in step 1
        foreach ($products as $product) {
            $validStatuses = collect(ImportStatus::valueArray());
            $currentStatus = strtolower($product->status ?? '');
            $currentStatus = $currentStatus === 'success' 
                ? ImportStatus::FINISHED->value  
                : $currentStatus;
            $newStatus = $validStatuses->contains($currentStatus)
                ? $currentStatus
                : ImportStatus::PENDING->value;

            // update the status, if one fails set the status to 
            // the default value
            Post::where('id', $post->id)
                ->update(['status' => $newStatus]);
        }
    }

    private function changeStatusToEnum(): void
    {
        // note: enums cannot be changed with migrations. 
        //       It has to be done with a DB statement
        $validEnumValues = ImportStatus::valueList("', '");
        $defaultValue = ImportStatus::PENDING->value;
        $query = "ALTER TABLE posts";
        $query .= "MODIFY COLUMN status enum('{$validEnumValues}') ";
        $query .= "DEFAULT '{$defaultValue}'";
        DB::statement($query);
    }
};

Update current references to the class constants to the enum value

A little drawback is that I can no longer refer to the values as ImportStatus::validating as that is now returning an enum instead of a string.

To get the value of an enum you have to call the value property on it: ImportStatus::validating->value

So change your codebase by replacing ImportStatus::validating to ImportStatus::validating->value

Laravel migration change foreign id to be nullable

If you created a foreign key in your database which should have been nullable, you have to create a database migration to fix that.

To make your foreign key nullable, you first need to delete the Foreign Key constraint, then change the field to be nullable and then create the Foreign Key constraint again.

<?php

return new class extends Migration {
    public function up(): void
    {
        Schema::table('retailers', function (Blueprint $table) {
            $table->dropForeign('retailers_import_id_foreign');

            $table->unsignedBigInteger('import_id')
                ->nullable(true)
                ->change();

            $table->foreign('import_id')
                ->references('id')
                ->on('import_files')
                ->nullOnDelete()
                ->cascadeOnUpdate();
        });
    }
};

Create related data with Pest, Laravel and factories

Setting up the related testdata when creating Pest tests always keeps me searching for the syntax.
Therefore, here a little reminder to self with links to the appropriate info in the Laravel documentation.

HasMany relations: User hasMany Post

// hasMany relation: User has many Posts - post.user_id is set
$user = User::factory()
  ->has(Post::factory()->count(3))
  ->create();

BelongsTo relations (inverse of the hasMany): Post belongsTo User => for()

// belongsTo: post.user_id is set
$post = Post::factory()
  ->for(User::factory())
  ->create();

Many to Many: User belongsToMany Role => has() and hasAttached()

// belongsToMany: using the pivot table. NOTE the array as first argument!
$user = User::factory()
  ->hasAttached([$tag], [<pivot fields>], 'roles')
  ->create();

Browscap with PHP

In order to get info about your clients browser, you need to install browscap.

ERROR: get_browser(): browscap ini directive not set

NOTE: you get this same error for different reasons! Check your logfiles to figure out what is the real reason for this error.

Reasons I encountered:

Browscap was not installed

To install Browscap on my Ubuntu (Docker image), I used the following site browscap.org.

It comes down to:

  1. download the ini file
  2. update (the correct! => fpm) php.ini file to load browscap
  3. restart the webserver

In the terminal (or in your Dockerfile):

# install browscap to get browser information of the client
curl https://browscap.org/stream?q=PHP_BrowsCapINI --output ${PHPDIR}/mods-available/php_browscap.ini

# add it to php.ini under the [browscap] directive
sed -i "s|;browscap = extra/browscap.ini.*|browscap = \"${PHPDIR}/mods-available/php_browscap.ini\"|g" ${PHPDIR}/fpm/php.ini

Browscap ini file was not included in php.ini

You can check whether PHP found the browscap file by

  • ensuring you entered the correct path to the file in the step above
  • ensuring the webserver has read permissions for the file
  • place phpinfo() on a page and search for browscap. It should be mentioned there
browscap mentioned in phpinfo()

Calling get_browser() with the wrong arguments

This is a funky one as the ini directive is set.

A look at the laravel log helped: get_browser(): HTTP_USER_AGENT variable is not set, cannot determine user agent name

I used get_browser(null, true) as I found in an online example, but it really needs the user agent as the first argument.

I fixed it by using: `

get_browser($request->userAgent(), true)

Note that I use Laravel, hence the $request->userAgent(). You can replace this with $_SERVER['HTTP_USER_AGENT'] just as well.

Other useful links

If this didn’t work out, you might info about your usecase somewhere on these pages:

Laravel order records by days until date – like the next birthday

You might want to order your users by ‘days until their birthday’.

People having their birthday come first, people with no birthday registered (NULL values), come last.

// in User model
public static function getByBirthday()
{
  return User::query()
      ->select('user.*')
      ->selectRaw(
          '365.25 -
          (
            case
              WHEN TIMESTAMPDIFF(day, birthday, CURDATE()) = 0 THEN 364.25
              WHEN birthday IS NULL THEN 0
              ELSE TIMESTAMPDIFF(day, birthday, CURDATE())
            end
            mod 365.25
           ) AS days_till_birthday'
      )
      ->orderBy('days_till_birthday');
}

// use it in your code like
$usersByBirthday = User::getByBirthday()->get();

SQL: get number of days until next birthday

What if you have a birthdate and you want to order the records by number of days until the next birthday?

That is what this query does. It takes into account that the birthdate is in the past and you want to get the next birthday given the current date.

SELECT 
  birthday
  , TIMESTAMPDIFF(day, birthday, CURDATE())
  ,365.25 -
        (
          case
            WHEN TIMESTAMPDIFF(day, birthday, CURDATE()) = 0 THEN 364.25
            WHEN birthday IS NULL THEN 0
            ELSE TIMESTAMPDIFF(day, birthday, CURDATE())
          end
          mod 365.25
         ) AS days_till_birthday
FROM users
order by 365.25 -
        (
          case
            WHEN TIMESTAMPDIFF(day, birthday, CURDATE()) = 0 THEN 364.25
            WHEN birthday IS NULL THEN 0
            ELSE TIMESTAMPDIFF(day, birthday, CURDATE())
          end
          mod 365.25
         ) asc

It’s based off of this answer on StackOverflow: https://stackoverflow.com/a/51407757

The difference is that it takes also works for people having their birthday today and ordering the records having NULL values for birthday at the end.

So people without their birthday are places last, where normally the NULL records are ordered first.

1 2 3 9