Here is a collection of Laravel helpers you may find useful.
<?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);
}
}
}