Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

Laravel notification like Facebook

Laravel 8 database notification example

Today, I will give you an example of “Laravel 8 database notification in Laravel”, So you can easily apply it with your laravel 5, laravel 6, laravel 7, laravel 8, and Laravel 9 application.

First, what we’re doing here, This is the example :

send user register notification to admin in laravel

laravel database notification example

show notifications like Facebook in laravel

Need to Send Notification in Laravel

The laravel notification system not just supports mail but also goes smooth with the database, broadcasting, SMS, Slack, markdown, etc.

Notifications can be seen as a short and straightforward messages delivered to a user for giving vital info, events, or to evoke action in the application.

Notifications keep the existing users in the loop, and it boosts user engagement as well. This is also valuable from a user experience perspective.

Laravel notifications like Facebook

Notifications are required in almost every application, especially which fall in the category of the blog, CMS, e-commerce, social media, or any noted digital product.

Let’s see an example below -:

Registered user notification send to admin

In the given below example, we will create a user registration form where the user can register with email, phone, and password.

We will store the user information in the user’s table and along with the notifications table, and we will show all the notifications to the application admin by following a few simple steps.

Step 1. Generate Notifications DB Table

To make the notifications work, we need to create a DB table. Run this command:

php artisan notifications:table

It will generate a migration class. And then, this, the usual one:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateNotificationsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('notifications', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->string('type');
            $table->morphs('notifiable');
            $table->text('data');
            $table->timestamp('read_at')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('notifications');
    }
}
php artisan migrate
generate notification table migration

User.php

<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

Step 2. Create Notification Class

php artisan make:notification NewUserRegisterNotification

app\Notifications\NewUserRegisterNotification.php

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class NewUserRegisterNotification extends Notification
{
    use Queueable;
    public $user;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($user)
    {
        $this->user = $user;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['database'];
    }

    /**
     * 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 [
            'name'  => $this->user->name,
            'email' => $this->user->email,
            'phone' => $this->user->phone,
        ];
    }
}

Pass all the user-required parameters using the User Register Controller to store them in the notification table.

Create Controllers :

php artisan make:controller UserRegisterController
php artisan make:controller AdminController

routes\web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\UserRegisterController;
use App\Http\Controllers\AdminController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

#Store new user registered info into db and show notification to admin

Route::get('/user-register', [UserRegisterController::class,'register']);
Route::post('/user-register-store', [UserRegisterController::class,'postRegistration'])->name('user.registerd');
    

#Display all notifications to Admin

Route::get('/notification', [AdminController::class,'showNotificaton']);

#Notification mark as Read

Route::post('/mark-as-read',[AdminController::class, 'markNotification'])->name('markNotification');

app\Http\Controllers\UserRegisterController.php :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use\App\Models\User;
use Auth;
use Illuminate\Support\Facades\Hash;
use App\Notifications\NewUserRegisterNotification;

class UserRegisterController extends Controller
{
    public function register()
    {
        return view('notificationExample.register');
    }

    public function postRegistration(Request $request)
    {
        $request->validate([
            'name'  => 'required',
            'email' => 'required|email|unique:users',
            'phone' => 'required',
            'password' => 'required|min:5',
           ]);

           $user = new User;
           $user->name         = $request->name;
           $user->email         = $request->email;
           $user->phone       = $request->phone;
           $user->password  = Hash::make($request->password);
           $user->save();

           $notification = User::first();
           #store notification info into notifications table
           $notification->notify(new NewUserRegisterNotification($user));
           dd('user registered successfully, Notification send to Admin Successfully.');
        }
    }

resources\views\notificationExample\register.blade.php

user registered data store into notifications table and show to admin in laravel
      <div class="container">
         <div class="row justify-content-center">
            <div class="col-lg-6">
               <div class="main">
                  <h3><a>Send User Register notification to Admin in Laravel</a></h3>
                  <form role="form" action="{{route('user.registerd')}}" method="post">
                     @csrf
                     <div class="form-group">
                        <label for="userename">Name <span class="text-danger">*</span></label>
                        <input type="text" name="name" class="form-control">
                         @if ($errors->has('name'))
                        <span class="text-danger">{{ $errors->first('name') }}</span>
                        @endif
                     </div>
                     <div class="form-group">
                        <label for="useremail">Email <span class="text-danger">*</span></label>
                        <input type="email" name="email"  class="form-control">
                        @if ($errors->has('email'))
                        <span class="text-danger">{{ $errors->first('email') }}</span>
                        @endif
                     </div>
                      <div class="form-group">
                        <label for="phone">Phone <span class="text-danger">*</span></label>
                        <input type="text" name="phone"  class="form-control">
                        @if ($errors->has('phone'))
                        <span class="text-danger">{{ $errors->first('phone') }}</span>
                        @endif
                     </div>
                     <div class="form-group">
                        <label for="userpassword">Password <span class="text-danger">*</span></label>
                        <input type="password" name="password" class="form-control">
                         @if ($errors->has('password'))
                        <span class="text-danger">{{ $errors->first('password') }}</span>
                        @endif
                     </div>
                     <div class="form-group">
                     </div>
                     <button type="submit" class="btn btn btn-secondary">
                     Register
                     </button>
                  </form>
               </div>
            </div>
         </div>
      </div>

store user information into notifications table

Related article:- Create multiple route files in Laravel 8.

Users Table:-

store user information into users table

Now, with every new user registration, a notification will be saved to the database. Like this:

Notifications Table:-

store new registered user information into notifications table

Step 4. Show all the registered Notifications to the Admin

app\Http\Controllers\AdminController.php :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;
use Session;


class AdminController extends Controller
{

  public function showNotificaton()
    {
      $notifications = auth()->user()->unreadNotifications;
      return view('showNotification', compact('notifications'));
    }
    
    public function markNotification(Request $request)
    {
        auth()->user()
            ->unreadNotifications
            ->when($request->input('id'), function ($query) use ($request) {
                return $query->where('id', $request->input('id'));
            })
            ->markAsRead();

        return response()->noContent();
    }
}

resources\views\showNotification.blade.php

<div class="dropdown-menu dropdown-menu-right" role="alert" aria-labelledby="navbarDropdownMenuLink">
   @if ($notifications->count() > 0 )
   @foreach($notifications as $notification)
   <div class="alert alert-light" role="alert">
      <p class="dropdown-item"><b> {{ $notification->data['name'] }} </b>&nbsp; ({{ $notification->data['email'] }}) has just registered.   [{{  date('j \\ F Y, g:i A', strtotime($notification->created_at)) }}]</p>
      <a href="#"><button type="button" rel="tooltip" title="Mark as read" class="btn btn-danger btn-link btn-sm mark-as-read" data-id="{{ $notification->id }}">
      <i class="material-icons">close</i>
      </button>
      </a>
   </div>
   <hr>
   @endforeach
   <a href="#" class="dropdown-item" id="mark-all">
   Mark all as read
   </a>
   @else
   <p class="dropdown-item">There are no new notifications</p>
   @endif
</div>

Here’s how it looks:

show all the registered user information to admin dashboard

Step 5. Laravel notification mark as read

By database column notifications.read_at which is NULL by default, or will contain a timestamp if it was read.

Related article:- Change the timezone in Laravel.

So, to mark notifications as read, we just need to fill in that column. We will do that via AJAX calls from the dashboard and an Admin Controller.

routes\web.php

#Notification mark as Read
 
Route::post('/mark-as-read',[AdminController::class, 'markNotification'])->name('markNotification');

resources\views\showNotification.blade.php

<div class="dropdown-menu dropdown-menu-right" role="alert" aria-labelledby="navbarDropdownMenuLink">
   @if ($notifications->count() > 0 )
   @foreach($notifications as $notification)
   <div class="alert alert-light" role="alert">
      <p class="dropdown-item"><b> {{ $notification->data['name'] }} </b>&nbsp; ({{ $notification->data['email'] }}) has just registered.   [{{  date('j \\ F Y, g:i A', strtotime($notification->created_at)) }}]</p>
      <a href="#"><button type="button" rel="tooltip" title="Mark as read" class="btn btn-danger btn-link btn-sm mark-as-read" data-id="{{ $notification->id }}">
      <i class="material-icons">close</i>
      </button>
      </a>
   </div>
   <hr>
   @endforeach
   <a href="#" class="dropdown-item" id="mark-all">
   Mark all as read
   </a>
   @else
   <p class="dropdown-item">There are no new notifications</p>
   @endif
</div>
<script>
   function sendMarkRequest(id = null) {
       return $.ajax("{{ route('markNotification') }}", {
           method: 'POST',
         
           data: {
             _token: '{{ csrf_token() }}',
               id
           }
       });
   }
   $(function() {
       $('.mark-as-read').click(function() {
           let request = sendMarkRequest($(this).data('id'));
           request.done(() => {
               $(this).parents('div.alert').remove();
           });
       });
       $('#mark-all').click(function() {
           let request = sendMarkRequest();
           request.done(() => {
               $('div.alert').remove();
           })
       });
   });
 </script>

app\Http\Controllers\AdminController.php :

public function markNotification(Request $request)
    {
        auth()->user()
            ->unreadNotifications
            ->when($request->input('id'), function ($query) use ($request) {
                return $query->where('id', $request->input('id'));
            })
            ->markAsRead();
 
        return response()->noContent();
    }

We learned the “Laravel 8 database notification example”, I hope this article will help you with your Laravel application Project.

Read also:- Delete the previous image from the folder when updated by a new image in Laravel.