codezero / laravel-flash
Laravel 的简洁闪存消息系统。
Requires
- php: ^8.1
- illuminate/session: ^10.0|^11.0
- illuminate/support: ^10.0|^11.0
Requires (Dev)
- orchestra/testbench: ^8.0|^9.0
- phpunit/phpunit: ^10.5
README
使用 Laravel 将闪存消息发送到会话中。
🧩 功能
- 闪存多个消息。
- 使用内置通知级别(成功、错误、...)或自定义自己的。
✅ 要求
- PHP >= 8.1
- Laravel >= 10.0
📦 安装
composer require codezero/laravel-flash
Laravel 将自动注册 ServiceProvider。
🛠 使用
在你的视图中某个地方,包含闪存通知部分
@include('flash::notifications')
然后你可以在控制器中向会话中发送消息。
flash()->success('Update succeeded!');
你也可以使用外观
\CodeZero\Flash\Facades\Flash
而不是flash()
辅助函数。
消息将在下一次页面加载时显示一次。
🚨 通知级别
你可以使用内置的通知级别
flash()->info('info message'); flash()->success('success message'); flash()->warning('warning message'); flash()->error('error message');
或者你可以指定一个自定义级别
flash()->notification('message', 'level');
🔖 渲染通知
自定义通知视图
如果你想要自定义模板,你可以发布视图
php artisan vendor:publish --provider="CodeZero\Flash\FlashServiceProvider" --tag="views"
你可以在 resources/views/vendor/flash
中找到这些视图。
内置通知级别的默认视图
一个通知将使用与通知级别名称对应的视图文件来渲染。
所以 flash()->success('message')
将加载一个 success.blade.php
视图文件。
这些视图位于 resources/views/vendor/flash/notifications
。
自定义通知级别的默认视图
如果包视图文件夹中找不到相应的文件,则将使用 default.blade.php
视图文件。
所以 flash()->notification('message', 'custom')
将加载 default.blade.php
视图文件。
此视图位于 resources/views/vendor/flash/notifications
。
为自定义通知级别添加视图
要为自定义级别添加视图文件,请在 resources/views/vendor/flash/notifications
中创建它们。
覆盖默认通知视图
你可以覆盖用于闪存通知的视图文件
// use 'resources/views/custom.blade.php' instead of // 'resources/views/vendor/flash/notifications/success.blade.php' flash()->success('message')->setView('custom');
指定的视图名称相对于你的应用程序视图文件夹 resources/views
。
在视图中访问通知值
通知视图将有一个 $notification
变量,它是一个 \CodeZero\Flash\Notification
实例。
这让你可以访问
{{ $notification->message }} {{ $notification->level }}
🔧 创建您自己的自定义闪存类
如果你不想使用内置的通知级别并想创建自己的,你可以扩展 \CodeZero\Flash\BaseFlash
类。
<?php namespace App; use CodeZero\Flash\BaseFlash; class YourCustomFlash extends BaseFlash { /** * Flash a notification. * * @param string $message * * @return \CodeZero\Flash\Notification */ public function danger($message) { return $this->notification($message, 'danger'); } }
然后更改你的 app/Providers/AppServiceProvider
的 register
方法中的 flash
绑定
public function register() { $this->app->bind('flash', \App\YourCustomFlash::class); }
⚙️ 发布配置文件
php artisan vendor:publish --provider="CodeZero\Flash\FlashServiceProvider" --tag="config"
现在你可以在 config
文件夹中找到一个 flash.php
文件。
🚧 测试
composer test
☕️ 致谢
🔓 安全
如果你发现任何与安全相关的问题,请给我发邮件,而不是使用问题跟踪器。
📑 更新日志
有关此包的所有显著变更的完整列表可以在 发布页面 上找到。
📜 许可证
麻省理工学院许可证(MIT)。请参阅许可证文件以获取更多信息。