Las notificaciones en Laravel 5 nos permiten además del envío por correo electrónico el envío de SMS (a través de Nexmo) y Slack..
Por si fuera poco, las notificaciones también pueden almacenarse en una base de datos para que se muestren en su interfaz web, pero este tema ya lo trataremos en otra entrada.
En este tutorial vamos a ver cómo enviar notificaciones en Laravel 5 a usuarios registrados pero también a usuarios no registrados, ¿por qué digo a usuarios no registrados?, fácil, porque por defecto, las notificaciones en Laravel 5, siempre deben enviarse a usuarios registrados. Crear notificaciones con Artisan Crear notificaciones en Laravel 5 es muy sencillo gracias al comando artisan, ejecutando el siguiente comando tenemos suficiente. php artisan make:notification NewNotification El comando anterior habrá creado el archivo app/Notifications/NewNotification.php con el siguiente código, una clase 100% funcional para enviar notificaciones.
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
class NewNotification extends Notification
{
use Queueable;
/**
* Create a new notification instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->line('The introduction to the notification.')
->action('Notification Action', url('/'))
->line('Thank you for using our application!');
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
Enviar notificaciones a usuarios registrados En el modelo User, si lo abrimos, veremos que por defecto se utiliza un Trait llamado Notifiable el cual a su vez utiliza el Trait RoutesNotifications y éste contiene el método notify, el cual podemos utilizar de la siguiente forma.
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
/**
* App\User
*
* @property-read \Illuminate\Notifications\DatabaseNotificationCollection|\Illuminate\Notifications\DatabaseNotification[] $notifications
* @mixin \Eloquent
*/
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'username', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function newNotification () {
$this->notify(new Notification);
}
}
Por lo tanto, podemos ver en el método newNotification que estamos enviando una notificación a un usuario ya registrado, sólo por llamar a ese método y configurar en nuestro caso las credenciales de email del archivo .env tenemos suficiente, la notificación será enviada y todo estará funcionando perfectamente. Enviar notificaciones fuera del modelo User Aunque es algo bastante obvio, prefiero no dar nada por hecho, así que vamos a poner un sencillo ejemplo para enviar nuestra notificaciones por ejemplo desde el sistema de rutas.
<?php
Route::get('notify', function () {
$user = \App\User::find(1);
$user->notify(new \App\Notifications\NewNotification());
});Enviar notificaciones a usuarios no registrados Algo que también puede resultar útil es enviar una notificación a usuarios que no estén registrados en nuestra aplicación, para ello, simplemente deberíamos utilizar el siguiente código.
<?php
Route::get('notify', function () {
(new User)->forceFill([
'name' => request('name'),
'email' => request('email'),
])->notify(new \App\Notifications\NewNotification());
});
Con (new User)->forceFill podemos crear un usuario no persistente pero funcional para las notificaciones :). Paso de datos a las notificaciones Si queremos utilizar algún dato dentro de nuestras notificaciones simplemente debemos pasar esta información al constructor y establecer estos datos cómo propiedades de la clase Notificacion.
NewNotification.php
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
class NewNotification extends Notification
{
use Queueable;
/**
* @var string
*/
protected $token;
/**
* Create a new notification instance.
*
* @param string $token
*/
public function __construct(string $token)
{
$this->token = $token;
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->line('The introduction to the notification.')
->action('Notification Action', url('/' . $this->token))
->line('Thank you for using our application!');
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}routes.php
<?php
Route::get('notify', function () {
$user = \App\User::find(2);
$token = md5(microtime());
$user->notify(new \App\Notifications\NewNotification($token));
});Personalizar la template de notificaciones Si además quieres personalizar y modificar la template de notificaciones, lo más sencillo es publicar el recurso con el siguiente comando. php artisan vendor:publish Una vez hecho, selecciona laravel-notifications.
Este comando habrá creado el archivo resources/views/vendor/notifications/email.blade.php el cual será utilizado para el envío de notificaciones y lo podrás modificar a tus necesidades.
Eso es todo, espero que te haya parecido útil e interesante el trabajo con Notificaciones en Laravel 5.
Curso Laravel 12
Completo 2026
El único curso 100% actualizado que incluye Laravel 12, Livewire 3, Vue 3, React 19 e Inertia 2. Aprende con proyectos reales y las últimas funcionalidades.
star Incluido en cualquier suscripción