Introduction
In this article, we will create a notification system using Livewire. Notifications are crucial for informing users about key events in an application. By using Laravel for the backend and Livewire for dynamic and interactive front-end components, we can create an efficient and responsive solution.
What is Livewire?
Livewire is a full-stack framework for Laravel that makes creating dynamic components very simple without leaving the Laravel ecosystem. This gives your users a more dynamic and responsive experience.
Key Features of Livewire
Full-Stack Framework: Livewire allows you to build dynamic interfaces using Laravel without writing a single line of JavaScript. It seamlessly handles both the front-end and back-end.
Component-Based: Livewire uses components to encapsulate the logic and presentation of specific parts of your application, making it easier to manage and reuse code.
Reactivity: Livewire components are reactive, meaning they automatically update the UI when the underlying data changes, providing a smooth and interactive user experience.
Server-Side Rendering: Livewire performs server-side rendering, ensuring fast initial page loads and SEO-friendly content. Subsequent interactions are handled via AJAX requests.
Event Handling: Livewire supports event handling, allowing components to communicate with each other and respond to user actions in real-time.
Validation: Livewire integrates seamlessly with Laravel's validation system, making it easy to validate user input and display error messages.
Lifecycle Hooks: Livewire provides lifecycle hooks that allow you to run code at specific points in a component's lifecycle, such as when it is mounted, updated, or destroyed.
Alpine.js Integration: Livewire integrates well with Alpine.js, a minimal JavaScript framework for adding interactivity to your components.
File Uploads: Livewire simplifies file uploads by handling the process on the server side, reducing the complexity of managing file uploads in your application.
Testing: Livewire components can be tested using Laravel's testing tools, ensuring that your dynamic interfaces are reliable and bug-free.
Project Configuration
Step 1: Installing Laravel
Let's get started by installing Laravel using Composer. ๐
composer create-project laravel/laravel notification
Step 2: Configuring Livewire
Let's add Livewire to your Laravel project:
- Installing Livewire
composer require livewire/livewire
- Esure Alpine.js is not already installed
If Alpine.js is already installed in your application, remove it to prevent conflicts with Livewire, as having Alpine.js loaded twice will cause issues; for instance, if you used the Laravel Breeze "Blade with Alpine" starter kit, remove Alpine.js from
resources/js/app.js
.
- The layout view
We'll need a layout file to load the CSS file and add some basic styling. Since Livewire and Alpine now automatically inject their scripts and styles, we don't even need to load those in the layout! We'll create the layout as an anonymous Blade component at resources/views/components/layout.blade.php
.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Create Category</title>
</head>
<body>
<div>{{ $slot }}</div>
</body>
</html>
Step 3: Setup Database
Open your .env file and tweak the settings to set up your database. Here's a simple example using SQLite:
DB_CONNECTION=sqlite
DB_DATABASE=database.sqlite
You can create an SQLite database by simply running:
touch /path/to/database.sqlite
For this example, we will create a category. Let's generate the Category
model along with the categories
migration.
php artisan make:model Category --migration
In the migration file database/migrations/xxxx_xx_xx_create_categories_table.php
, let's define the columns we need:
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('description')->nullable();
$table->boolean('status')->default(false);
$table->timestamps();
});
}
php artisan migrate
In the Category
model, let's set up the table properties like this:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use HasFactory;
protected $fillable = [
'name',
'description',
'status'
];
public function casts()
{
return [
'status' => 'boolean'
];
}
}
Step : 4 Create Category Component
Livewire provides a fun and interactive component system that we can use. Here's how to get started:
- Let's create our Livewire component
CreateCategory.php
inapp\Livewire\
. At the same time, another file calledcreate-category.blade.php
will be created inresources/views/livewire/
php artisan make:livewire create-category
- Now, let's open the
CreateCategory.php
file and check out the code.
<?php
namespace App\Livewire;
use Illuminate\Contracts\View\View;
use Livewire\Component;
class CreateCategory extends Component
{
public function render(): View
{
return view('livewire.create-category');
}
}
And here's what the Blade file resources/views/livewire/create-category.blade.php
looks like:
<div>
{{-- Success is as dangerous as failure. --}}
</div>
Now let's add the form to resources/views/livewire/create-category.blade.php
file so users can submit their categories.
<div>
<form wire:submit.prevent="submit">
<div>
<label for="name">Name</label>
<input
type="text"
id="name"
name="name"
wire:model="name"
>
</div>
<div>
<label for="name">Description</label>
<textarea
name="description"
id="description"
wire:model="description"
></textarea>
</div>
<button type="submit">Submit</button>
</form>
</div>
Let's add the logic to create and manage categories in a Livewire component, like CreateCategory
:
<?php
namespace App\Livewire;
use App\Models\Category;
use Illuminate\Contracts\View\View;
use Livewire\Attributes\Validate;
use Livewire\Component;
class CreateCategory extends Component
{
#[Validate(
'required',
'string',
'max:255',
'unique:categories,name',
)]
public string | null $name = '';
#[Validate(
'nullable',
'string',
'max:255',
)]
public string | null $description = '';
public function render(): View
{
return view('livewire.create-category');
}
public function submit(): void
{
$this->validate();
Category::query()
->create([
'name' => $this->name,
'description' => $this->description,
'status' => false
]);
$this->redirect(route('category'), true);
}
}
Step 5: Dispatching Events
To dispatch an event from a Livewire component, use the dispatch()
method with the event name and any extra data. The example below shows how to dispatch a success
event from a CreateCategory
component.
<?php
namespace App\Livewire;
use App\Models\Category;
use Illuminate\Contracts\View\View;
use Livewire\Attributes\Validate;
use Livewire\Component;
use function Livewire\Volt\title;
class CreateCategory extends Component
{
public function submit(): void
{
// ...
$this->dispatch('success', title: "New category create");
}
}
To learn more, please refer to the Livewire documentation Livewire Dispatch Event.
- Listening for Livewire Events from Global JavaScript
You can also listen for Livewire events globally using Livewire.on
from any script in your application:
<script>
document.addEventListener('livewire:init', () => {
Livewire.on('success', (event) => {
// ..
});
});
</script>
The above snippet listens for the success
event dispatched from any component on the page.
To display notifications in our application, we need JavaScript libraries that allow us to show notifications like Facebook, Twitter, LinkedIn, and other platforms. In our tutorial, we will use the pushjs
library. For more details, refer to the PushJs documentation.
npm install push.js --save
Next, we will modify the resources/js/app.js
file and add the following code. et ajoutons un nouveau fichier js portant le nom de Notification.js
import {errorNotification, notification} from "@/Notification.js";
const handleEvent = (type, handler) => Livewire.on(type, handler);
document.addEventListener('livewire:init', () => {
handleEvent('success', notification);
handleEvent('error', errorNotification);
});
Here is the code that you'll place in Notification.js
import Push from 'push.js'
export const notification = (event) => {
Push.create("Success Notification",{
body: `${event}`,
icon: '/icon.png' ?? '',
timeout: 5000,
onClick: function () {window.focus();this.close(); }
})
}
Step 5: Run Project
To run the Laravel project, we need to execute the following command:
php artisan serve
For starting front:
npm run dev
Conclusion
By following this guide, you've set up a complete and responsive notification system using Livewire. This system can be customized to fit your application's specific needs, giving your users a rich and interactive experience. Thanks to the integration of Livewire and Laravel, you can now manage notifications efficiently while maintaining a smooth and responsive user interface. Keep exploring Livewire's features to make your application even better and provide an awesome experience for your users.