Skip to content

Instantly share code, notes, and snippets.

@joaorbrandao
Last active November 30, 2020 23:47
Show Gist options
  • Select an option

  • Save joaorbrandao/38ed6ddd430c4191bd5f2b608371c53e to your computer and use it in GitHub Desktop.

Select an option

Save joaorbrandao/38ed6ddd430c4191bd5f2b608371c53e to your computer and use it in GitHub Desktop.
Laravel Enums
<?php
namespace App\Enums;
use App\Traits\Enum;
final class AlertMessage
{
use Enum;
const SUCCESS = 'success';
const ERROR = 'danger';
const WARNING = 'warning';
const INFO = 'info';
}
<?php
namespace App\Traits;
use ReflectionClass;
trait Enum
{
/**
* Get all constants of the enum.
*
* @return array
* @throws \ReflectionException
*/
public static function all()
{
$reflectionClass = new ReflectionClass(self::class);
return $reflectionClass->getConstants();
}
/**
* Get all constant values of the enum.
*
* @return array
* @throws \ReflectionException
*/
public static function values()
{
$reflectionClass = new ReflectionClass(self::class);
return array_values($reflectionClass->getConstants());
}
/**
* Get the first constant of the enum.
*
* @return array
* @throws \ReflectionException
*/
public static function first()
{
$reflectionClass = new ReflectionClass(self::class);
return array_first($reflectionClass->getConstants());
}
/**
* Get the last constant of the enum.
*
* @return array
* @throws \ReflectionException
*/
public static function last()
{
$reflectionClass = new ReflectionClass(self::class);
return array_last($reflectionClass->getConstants());
}
}
<?php
namespace App\Http\Controllers;
use App\Enums\AlertMessage;
use Illuminate\Http\Request;
class TestController extends Controller
{
public function store(Request $request)
{
// ...
return redirect()->withErrors([
'alertMessage' => AlertMessage::ERROR
]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment