Skip to content

Instantly share code, notes, and snippets.

@bhuvidya
Last active January 2, 2021 02:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhuvidya/f6266ec88d86589a2dcb44c1a761e835 to your computer and use it in GitHub Desktop.
Save bhuvidya/f6266ec88d86589a2dcb44c1a761e835 to your computer and use it in GitHub Desktop.
A collection of handy Laravel helpers. I've organised into general categories.

Laravel Helper Collection

Here is a collection of Laravel helpers you may find useful.

Dump

dump_if() - an extended dump()

<?php

use Illuminate\Console\Command;

if (! function_exists('dump_if')) {
    /**
     * Do a dump if a condition is true. Also, support output to
     * an Illuminate\Console\Command instance. And support printf-like args.
     * If you want to output to a command instance, pass it as the last parameter,
     * along with an optional command output method ('info', 'warn', 'error' etc).
     * So if using from within a database seeder, you can use $seeder->command as
     * the command instance.
     *
     * Examples:
     *
     *      dump_if($cond, $data);
     *      dump_if($cond, 'My user id is %05d', Auth::user()->getKey())
     *      dump_if($cond, 'My user id is %05d', Auth::user()->getKey(), $seeder->command)
     *      dump_if($cond, 'My user id is %05d', Auth::user()->getKey(), $seeder->command, 'warn')
     *
     * @param bool $cond
     * @param array ...$args
     */
    function dump_if($cond, ...$args)
    {
        if (!$cond) {
            return;
        }
        if (!$args) {
            return;
        }

        $cnt = count($args);
        $cmd = null;
        $cmd_method = 'info';
        $dump_args = $args;

        if ($cnt >= 2 && $args[$cnt-1] instanceof Command) {
            $cmd = $args[$cnt-1];
            $dump_args = array_slice($args, 0, $cnt-1);
        } elseif ($cnt >= 3 && $args[$cnt-2] instanceof Command) {
            $cmd = $args[$cnt-2];
            $cmd_method = $args[$cnt-1];
            $dump_args = array_slice($args, 0, $cnt-2);
        }

        if (count($dump_args) >= 2) {
            $dump_args = [ sprintf(...$dump_args) ];
        }

        if ($cmd) {
            $cmd->$cmd_method(...$dump_args);
        } else {
            dump(...$dump_args);
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment