Last active
November 30, 2020 23:47
-
-
Save joaorbrandao/38ed6ddd430c4191bd5f2b608371c53e to your computer and use it in GitHub Desktop.
Laravel Enums
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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'; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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()); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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