Skip to content

Instantly share code, notes, and snippets.

@drianoaz
Created July 20, 2018 12:56
Show Gist options
  • Save drianoaz/69777df7b99ffead766eec80c0ee9a29 to your computer and use it in GitHub Desktop.
Save drianoaz/69777df7b99ffead766eec80c0ee9a29 to your computer and use it in GitHub Desktop.
Laravel old helper for database models
if (! function_exists('old_helper')) {
/**
* Retrieve an old input item and set a
* default value with helper
*
* @param $oldKey
* @param null $target
* @param null $targetKey
* @param callable|null $callback
* @return mixed
*/
function old_helper($oldKey, $target = null, $targetKey = null, callable $callback = null)
{
$value = data_get($target, $targetKey);
if (! is_null($callback) && ! is_null($value)) {
$value = $callback($value);
}
return old($oldKey, $value);
}
}
$user = \App\User::find(1);
// echo old name only
echo old_helper('name');
// echo name from user if old name not exists
echo old_helper('name', $user, 'name');
// format values in a callback functions - this works only if target key is not null
echo old_helper('name', $user, 'created_at', function($value) {
return $value->format('d/m/Y')
});
// echo value from a relationship
echo old_helper('name', $user, 'roles.name');
echo old_helper('name', $user, 'long.example.relationships');
// echo null if target key not exists
echo old_helper('name', $user, 'nonexistent.key.value');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment