diff --git a/docs/_data/manifest.json b/docs/_data/manifest.json index c381122f..22f51d5f 100644 --- a/docs/_data/manifest.json +++ b/docs/_data/manifest.json @@ -1,5 +1,5 @@ { - "dist/main.css": "/dist/main.9eb3dd2b.css", + "dist/main.css": "/dist/main.0e8a2b07.css", "dist/main.js": "/dist/main.3be5bc06.js", "dist/455.3a7b4474.css": "/dist/455.3a7b4474.css", "dist/455.095e6545.js": "/dist/455.095e6545.js", diff --git a/docs/_layouts/laravel.html b/docs/_layouts/laravel.html new file mode 100644 index 00000000..0f74bba4 --- /dev/null +++ b/docs/_layouts/laravel.html @@ -0,0 +1,1682 @@ +--- +layout: default +--- + +
+ PHPFlasher + helps you easily add flash notifications to your Laravel projects, improving user feedback with minimal setup. +
+ + ++ If you need to use PHP < v8.2 or Laravel < v11.0, use + PHPFlasher v1 instead. + It supports PHP ≥ v5.3 and Laravel ≥ v5.0. + + Check out the v1 documentation here + . +
++ PHPFlasher is modular. You can install only the parts you need. +
+Run this command to install it:
+ + +composer require php-flasher/flasher-laravel
+ After installing, run this command to set up the required assets:
+ +php artisan flasher:install
+ That's it! No need for complex configuration - + PHPFlasher works right out of the box with sensible defaults. +
++ PHPFlasher works seamlessly with Laravel's service container and will be automatically discovered. No additional configuration is needed. +
++ Here's a basic example of using PHPFlasher in a Laravel controller: +
+ + +namespace App\Http\Controllers;
+
+use App\Models\Product;
+use Illuminate\Http\Request;
+
+class ProductController extends Controller
+{
+ public function store(Request $request)
+ {
+ // Validate the request
+ $validated = $request->validate([
+ 'name' => 'required|string|max:255',
+ 'price' => 'required|numeric',
+ ]);
+
+ // Create the product
+ Product::create($validated);
+
+ // Add a success notification
+ flash()->success('Product created successfully!');
+
+ return redirect()->route('products.index');
+ }
+}
+ + PHPFlasher + provides two ways to create notifications: +
+flash()->success('Message');
+ use Flasher\Laravel\Facade\Flasher; Flasher::success('Message');
+ PHPFlasher supports different types of notifications: +
+ +// Success message
+flash()->success('Your changes have been saved!');
+
+// Error message
+flash()->error('Something went wrong!');
+
+// Warning message
+flash()->warning('Please review your data before proceeding.');
+
+// Info message
+flash()->info('The system will be down for maintenance tonight.');
+ Your changes have been saved!
+Something went wrong!
+Please review your data before proceeding.
+The system will be down for maintenance tonight.
+You can add a title to your notifications:
+ +flash()->success('Your profile has been updated successfully.', 'Profile Updated');
+ Your profile has been updated successfully.
+Customize your notifications with various options:
+ +flash()
+ ->option('position', 'top-center') // Position on the screen
+ ->option('timeout', 5000) // How long to display (milliseconds)
+ ->option('rtl', true) // Right-to-left support
+ ->success('Your changes have been saved!');
+ Control how long notifications display with the timeout option (milliseconds).
Set to 0 to require manual dismissal.
Choose from various animations:
++ Here are some common examples of using PHPFlasher in your Laravel applications. +
+ + +A complete example showing notifications for Create, Read, Update, and Delete operations:
+ +namespace App\Http\Controllers;
+
+use App\Models\Post;
+use Illuminate\Http\Request;
+
+class PostController extends Controller
+{
+ public function store(Request $request)
+ {
+ $validated = $request->validate([
+ 'title' => 'required|string|max:255',
+ 'content' => 'required|string',
+ ]);
+
+ Post::create($validated);
+
+ flash()->success('Post created successfully!', 'Success');
+
+ return redirect()->route('posts.index');
+ }
+
+ public function update(Request $request, Post $post)
+ {
+ $validated = $request->validate([
+ 'title' => 'required|string|max:255',
+ 'content' => 'required|string',
+ ]);
+
+ $post->update($validated);
+
+ flash()->success('Post updated successfully!');
+
+ return redirect()->route('posts.index');
+ }
+
+ public function destroy(Post $post)
+ {
+ $post->delete();
+
+ flash()->info('Post was deleted');
+
+ return redirect()->route('posts.index');
+ }
+}
+ + Use the same notification style and wording for similar operations across your application. This provides a consistent user experience. +
+Show validation errors with meaningful notifications:
+ +namespace App\Http\Controllers\Auth;
+
+use App\Http\Controllers\Controller;
+use App\Models\User;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Hash;
+
+class RegisterController extends Controller
+{
+ public function register(Request $request)
+ {
+ try {
+ $validated = $request->validate([
+ 'name' => 'required|string|max:255',
+ 'email' => 'required|email|unique:users,email',
+ 'password' => 'required|min:8|confirmed',
+ ]);
+
+ User::create([
+ 'name' => $validated['name'],
+ 'email' => $validated['email'],
+ 'password' => Hash::make($validated['password']),
+ ]);
+
+ flash()->success('Your account has been created successfully!', 'Welcome!');
+
+ return redirect()->route('login');
+ } catch (\Illuminate\Validation\ValidationException $e) {
+ // Return back with validation errors
+ flash()->error('Please fix the errors in the form.', 'Registration Failed');
+
+ return back()->withErrors($e->validator)->withInput();
+ }
+ }
+}
+ PHPFlasher works seamlessly with AJAX requests. It automatically displays notifications from JSON responses:
+ +namespace App\Http\Controllers\Api;
+
+use App\Http\Controllers\Controller;
+use Illuminate\Http\Request;
+
+class ApiController extends Controller
+{
+ public function saveData(Request $request)
+ {
+ try {
+ // Process data...
+ $success = true; // Assuming operation succeeded
+
+ if ($success) {
+ flash()->success('Data saved successfully!');
+
+ return response()->json([
+ 'status' => 'success',
+ 'message' => 'Data saved successfully!'
+ ]);
+ } else {
+ flash()->error('Failed to save data');
+
+ return response()->json([
+ 'status' => 'error',
+ 'message' => 'Failed to save data'
+ ], 400);
+ }
+ } catch (\Exception $e) {
+ flash()->error('An error occurred: ' . $e->getMessage());
+
+ return response()->json([
+ 'status' => 'error',
+ 'message' => 'An error occurred'
+ ], 500);
+ }
+ }
+}
+ document.getElementById('saveForm').addEventListener('submit', function(e) {
+ e.preventDefault();
+
+ const formData = new FormData(this);
+
+ fetch('/api/save', {
+ method: 'POST',
+ body: formData,
+ headers: {
+ 'X-Requested-With': 'XMLHttpRequest'
+ }
+ })
+ .then(response => response.json())
+ .then(data => {
+ console.log('Success:', data);
+ // PHPFlasher will automatically display the notification
+ // No additional JS code needed!
+ })
+ .catch(error => {
+ console.error('Error:', error);
+ });
+});
+ + PHPFlasher automatically handles AJAX responses — notifications from the server appear without any additional code. This works with fetch, axios, jQuery, and other AJAX methods. +
+You can add notifications from middleware for actions like authorization:
+ +namespace App\Http\Middleware;
+
+use Closure;
+use Illuminate\Http\Request;
+
+class AdminAccessMiddleware
+{
+ public function handle(Request $request, Closure $next)
+ {
+ if (!$request->user() || !$request->user()->isAdmin()) {
+ flash()->error('You do not have access to this area.', 'Access Denied');
+ return redirect()->route('home');
+ }
+
+ return $next($request);
+ }
+}
+ If you want to change the default settings, you can publish the configuration file:
+ +php artisan flasher:install --config
+
+ This will create a file at
+ config/flasher.php
+ with the following content:
+
'flasher',
+
+ // Path to the main PHPFlasher JavaScript file
+ 'main_script' => '/vendor/flasher/flasher.min.js',
+
+ // List of CSS files to style your notifications
+ 'styles' => [
+ '/vendor/flasher/flasher.min.css',
+ ],
+
+ // Set global options for all notifications (optional)
+ // 'options' => [
+ // 'timeout' => 5000, // Time in milliseconds before the notification disappears
+ // 'position' => 'top-right', // Where the notification appears on the screen
+ // ],
+
+ // Automatically inject JavaScript and CSS assets into your HTML pages
+ 'inject_assets' => true,
+
+ // Enable message translation using Laravel's translation service
+ 'translate' => true,
+
+ // Map Laravel flash message keys to notification types
+ 'flash_bag' => [
+ 'success' => ['success'],
+ 'error' => ['error', 'danger'],
+ 'warning' => ['warning', 'alarm'],
+ 'info' => ['info', 'notice', 'alert'],
+ ],
+
+ // Set criteria to filter which notifications are displayed (optional)
+ // 'filter' => [
+ // 'limit' => 5, // Maximum number of notifications to show at once
+ // ],
+
+ // Define notification presets to simplify notification creation (optional)
+ // 'presets' => [
+ // 'entity_saved' => [
+ // 'type' => 'success',
+ // 'title' => 'Entity saved',
+ // 'message' => 'Entity saved successfully',
+ // ],
+ // ],
+];
+ [
+ 'position' => 'bottom-right',
+ ],
+];
+ [
+ 'timeout' => 8000, // 8 seconds
+ ],
+];
+ The default configuration works great for most projects. Only + customize if you need specific behaviors like:
++ PHPFlasher automatically converts Laravel's native session flash messages to PHPFlasher notifications, making migration easy: +
+ +// Your existing Laravel flash messages still work
+session()->flash('success', 'Changes were saved!');
+
+// Or with the helper
+$request->session()->flash('error', 'Something went wrong!');
+
+// They will be converted to PHPFlasher notifications automatically
+// You can gradually migrate your codebase to use PHPFlasher directly
+ You can create a preset for a custom notification that you want to reuse in multiple
+ places. Add a presets entry in
+ the configuration file.
+
+ Presets are pre-defined notification configurations that you can reuse throughout your application. They help maintain consistent messaging and reduce code duplication. +
+
+ For example, create a preset named entity_saved:
+
[
+ 'entity_saved' => [
+ 'type' => 'success',
+ 'message' => 'Entity saved successfully',
+ 'title' => 'Entity saved',
+ ],
+
+ 'payment_received' => [
+ 'type' => 'success',
+ 'message' => 'Payment of %amount% has been received.',
+ 'title' => 'Payment Confirmed',
+ 'options' => [
+ 'timeout' => 8000,
+ 'position' => 'top-center',
+ ],
+ ],
+
+ 'account_locked' => [
+ 'type' => 'error',
+ 'message' => 'Your account has been locked due to multiple failed attempts.',
+ 'title' => 'Security Alert',
+ 'options' => [
+ 'timeout' => 0, // Requires manual dismissal
+ 'position' => 'center',
+ ],
+ ],
+ ],
+];
+
+ To use the preset, call the preset()
+ method and pass the name of the preset:
+
namespace App\Http\Controllers;
+
+use App\Models\Book;
+use Illuminate\Http\Request;
+
+class BookController extends Controller
+{
+ public function store(Request $request)
+ {
+ // Save the book...
+
+ // Use a preset for the notification
+ flash()->preset('entity_saved');
+
+ return redirect()->route('books.index');
+ }
+}
+
+class PaymentController extends Controller
+{
+ public function confirm(Request $request)
+ {
+ // Process payment...
+
+ // Use a preset with parameters
+ flash()->preset('payment_received', [
+ 'amount' => '€50.00'
+ ]);
+
+ return redirect()->route('payment.receipt');
+ }
+}
+ The first example is the same as:
+ +namespace App\Http\Controllers;
+
+class BookController extends Controller
+{
+ public function store()
+ {
+ // Without preset, would need to do:
+ flash()->success('Entity saved successfully', 'Entity saved');
+
+ return redirect()->route('books.index');
+ }
+}
+ + CRUD Operations: + Create consistent notifications for create, update, delete operations +
++ User Feedback: Standardize welcome messages, payment confirmations, etc. +
++ Error Handling: Create consistent error notifications with custom styling +
++ Store all your notification presets in one place to ensure consistent messaging across your application. This makes it easy to update notification wording or styling globally. +
+You can create more flexible presets using parameters:
+ + [
+ 'order_created' => [
+ 'type' => 'success',
+ 'message' => 'Order #%order_id% has been created successfully. Total: %amount%',
+ 'title' => 'Order Created'
+ ],
+ ],
+];
+ Then use the preset with parameters:
+ +// Parameters are passed as an array
+flash()->preset('order_created', [
+ 'order_id' => '12345',
+ 'amount' => '$99.99'
+]);
+
+// This will display: "Order #12345 has been created successfully. Total: $99.99"
+ + PHPFlasher + integrates perfectly with Laravel's translation system, making it easy to display notifications in multiple languages. +
+ +Use the translate() method to set the language for a notification:
// Translation will automatically use the current locale from Laravel's App::getLocale()
+flash()->success('The resource was created');
+
+// Or explicitly specify a language
+flash()->translate('fr')->success('The resource was created');
+flash()->translate('ar')->success('The resource was created');
+ Define your translations in PHP files in the resources/lang/vendor/flasher/ directory:
'نجاح',
+ 'error' => 'خطأ',
+ 'warning' => 'تحذير',
+ 'info' => 'معلومة',
+
+ 'The resource was created' => 'تم إنشاء :resource',
+ 'The resource was updated' => 'تم تعديل :resource',
+ 'The resource was saved' => 'تم حفظ :resource',
+ 'The resource was deleted' => 'تم حذف :resource',
+
+ 'resource' => 'الملف',
+];
+ 'Success',
+ 'error' => 'Error',
+ 'warning' => 'Warning',
+ 'info' => 'Info',
+
+ 'The resource was created' => 'The :resource was created',
+ 'The resource was updated' => 'The :resource was updated',
+ 'The resource was saved' => 'The :resource was saved',
+ 'The resource was deleted' => 'The :resource was deleted',
+
+ 'resource' => 'resource',
+];
+ 'Succès',
+ 'error' => 'Erreur',
+ 'warning' => 'Avertissement',
+ 'info' => 'Information',
+
+ 'The resource was created' => 'La ressource :resource a été ajoutée',
+ 'The resource was updated' => 'La ressource :resource a été mise à jour',
+ 'The resource was saved' => 'La ressource :resource a été enregistrée',
+ 'The resource was deleted' => 'La ressource :resource a été supprimée',
+
+ 'resource' => '',
+];
+ + PHPFlasher + automatically handles right-to-left languages like Arabic and Hebrew. The layout adjusts based on the language: +
+ + +تمت العملية بنجاح.
+// Using Arabic language automatically enables RTL
+flash()
+ ->translate('ar')
+ ->success('Your request was processed successfully.', 'Congratulations!');
+
+// Or explicitly set RTL mode
+flash()
+ ->option('rtl', true)
+ ->success('Your request was processed successfully.', 'Congratulations!');
+ PHPFlasher automatically uses Laravel's current locale:
+ +// Set the locale in Laravel
+App::setLocale('fr');
+
+// PHPFlasher automatically uses the current locale
+flash()->success('The resource was created');
+
+// With parameters
+flash()->success(
+ trans('messages.welcome', ['name' => $user->name])
+);
+ You can use parameters in your translations:
+ +// In resources/lang/vendor/flasher/en/messages.php:
+// 'welcome.user' => 'Welcome, :name!'
+
+flash()
+ ->success(
+ trans('welcome.user', ['name' => $user->first_name])
+ );
+
+// Or directly with PHPFlasher (if using presets with placeholders)
+flash()->preset('welcome_user', ['name' => $user->first_name]);
+ + Store all user-facing notification messages in translation files rather than hardcoding them. This makes it much easier to update wording or add new languages later. +
+Choose from 6+ themes including Toastr, SweetAlert, Notyf, Noty and more.
+ + View themes + +Seamless integration with Laravel Livewire for dynamic notifications without page reload.
+ + Learn more + +Show notifications from AJAX responses automatically with JSON responses.
+ + Learn more + +Start using PHPFlasher today and + give your users beautiful notifications in minutes!
+