馃摙 Notificaciones y alertas en Laravel

馃摙 Notificaciones y alertas en Laravel

Aprende a enviar y mostrar notificaciones interactivas

Laravel facilita la creaci贸n de notificaciones que pueden enviarse por correo, base de datos o tiempo real. Aqu铆 aprender谩s c贸mo generar y mostrar alertas visuales e interactivas con ejemplos pr谩cticos.

馃敡 Crear una notificaci贸n

Laravel usa el comando make:notification para generar una nueva notificaci贸n:


php artisan make:notification NuevoComentario
  

Esto crea una clase en app/Notifications/. Ejemplo b谩sico:


namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;

class NuevoComentario extends Notification
{
    use Queueable;

    public function via($notifiable)
    {
        return ['mail', 'database'];
    }

    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->subject('Nuevo comentario en tu publicaci贸n')
                    ->line('Alguien ha comentado tu publicaci贸n.')
                    ->action('Ver comentario', url('/comentarios'))
                    ->line('Gracias por usar nuestra aplicaci贸n!');
    }

    public function toArray($notifiable)
    {
        return [
            'mensaje' => 'Tienes un nuevo comentario en tu publicaci贸n',
            'url' => '/comentarios'
        ];
    }
}
  

⚙️ Enviar una notificaci贸n desde el controlador


use App\Models\User;
use App\Notifications\NuevoComentario;

public function comentar($id)
{
    $usuario = User::find(1); // Usuario receptor
    $usuario->notify(new NuevoComentario());

    return back()->with('success', 'Notificaci贸n enviada correctamente');
}
  

馃 Mostrar notificaciones visuales (Ejemplo interactivo)

En este ejemplo puedes simular c贸mo se mostrar铆an las notificaciones y ver su contenido directamente.

馃摎 Ejemplo de c贸digo Blade para mostrar notificaciones reales


@foreach (auth()->user()->notifications as $notificacion)
  <div class="alert alert-info d-flex justify-content-between align-items-center">
    {{ $notificacion->data['mensaje'] }}
    <a href="{{ $notificacion->data['url'] }}" class="btn btn-sm btn-outline-primary">Ver</a>
  </div>
@endforeach
  
Consejo: Puedes marcar notificaciones como le铆das con $user->unreadNotifications->markAsRead() y mostrarlas en la interfaz para una mejor experiencia.

馃搵 En resumen:

  • Laravel permite enviar notificaciones por correo, base de datos o broadcast.
  • Puedes generar notificaciones con make:notification.
  • Los datos se almacenan en la tabla notifications.
  • Con JavaScript puedes mostrar notificaciones interactivas y simuladas como en este ejemplo.

Publicar un comentario

0 Comentarios