Home » Laravel Notification Tutorial With Example

Laravel Notification Tutorial With Example

Last updated on May 27, 2022 by

In this post, we will learn the Laravel notification tutorial with an example. We can send different kinds of notifications like SMS, Email, slack message, toast notification, custom messages, etc. Let’s just jump into it.

Step 1: Install Laravel

If you already have installed Laravel on your local machine then you can skip this step. You can easily install the fresh version of Laravel by running the below command in your terminal. You can give it any name but in this case, we will name it demo-app.

composer create-project --prefer-dist laravel/laravel demo-app

Step 2: Setup Database Connection

In this step, we will set up the MySQL database. Go to the .env file and insert the given below code inside of it.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

Step 3: Generate Notification Migration

We need notifications table to store the notification. We don’t need to create a table manually, Laravel provides it by default. You may use the notifications:table command to generate a migration with the proper table schema:

php artisan notifications:table
php artisan migrate

Step 4: Create Notification In Laravel

In Laravel, each notification is defined by a single class that is typically stored in the app/Notifications directory. Let’s run the below command to create a new notification.

php artisan make:notification InvoicePaid

The above command will create a new class in app/Notifications directory. Each notification class contains a via, toMail, and toDatabase methods.

app/Notifications/InvoicePaidNotification.php

<?php

namespace App\Notifications;

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


class InvoicePaidNotification extends Notification
{
    use Queueable;

    private $invoiceData;
    
    public function __construct($invoiceData)
    {
        $this->invoiceData = $invoiceData;
    }
    
    public function via($notifiable)
    {
        return ['mail','database'];
    }
    
    public function toMail($notifiable)
    {
        return (new MailMessage)                    
            ->name($this->invoiceData['title'])
            ->line($this->invoiceData['body'])
            ->action($this->invoiceData['buttonText'], $this->invoiceData['invoiceUrl'])
            ->line($this->invoiceData['thanks']);
    }
    
    public function toArray($notifiable)
    {
        return [
            'invoice_id' => $this->invoiceData['id']
        ];
    }
}

Step 5: Create Routes

We need to add routes in routes/web.php file to send the notification to the user on invoices paid via mail. So open the routes/web.php file and add the following route.

routes/web.php

<?php

use App\Http\Controllers\InvoiceController;
use Illuminate\Support\Facades\Route;

Route::get('invoice/{id}', [InvoiceController::class, 'show'])->name('show.invoice');

Route::post('invoice-paid', [InvoiceController::class, 'sendInvoicePaidNotification'])
    ->name('notify.invoice.paid');

Step 6: Create Controller

Let’s create a InvoiceController to create a controller run the below command:

php artisan make:controller InvoiceController

After running the above command a new file will be created in Controllers the directory, open it, and add the following code.

app/Http/Controllers/InvoiceController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Invoice;
use Notification;
use App\Notifications\InvoicePaidNotification;

class NotificationController extends Controller
{ 
    public function index()
    {
        $invoices = Invoice::where('user_id', auth()->user()->id)->get();

        return view('invoices', compact('invoices'));
    }

    public function show(Invoice $invoice)
    {
        return view('invoices', compact('invoice'));
    }
    
    public function sendInvoicePaidNotification(Request $request) 
    {   
        $request->validate([
            'invoice_id'=>'required|exists:invoices,id',
        ]);

        $user = auth()->user();

        $invoice = Invoice::find($request->invoice_id)->first();

        $invoice['buttonText'] = 'View Invoice';
        $invoice['invoiceUrl'] = route('show.invoice');
        $invoice['thanks'] = 'Your thank you message';
  
        Notification::send($user, new InvoicePaidNotification($invoice));
   
        return back()->with('You have successfully paid the invoice');
    }
}

Step 7: Output

Hurray! We have completed all steps to send Laravel notification. Let’s run the below command and see how it’s working.

php artisan serve

After running the above command, open your browser and visit the site below URL:

http://localhost:8000/invoices

Additionally, read our guide:

  1. Laravel: Blade Switch Case Statement Example
  2. Laravel: Switch Case Statement In Controller Example
  3. Laravel: Change Column Type In Migration
  4. 2fa Laravel With SMS Tutorial With Example
  5. How To Use Where Date Between In Laravel
  6. How To Add Laravel Next Prev Pagination
  7. Laravel Remove Column From Table In Migration
  8. Laravel: Get Month Name From Date
  9. Laravel: Increase Quantity If Product Already Exists In Cart
  10. How To Update Pivot Table In Laravel
  11. How To Install Vue In Laravel 8 Step By Step
  12. How To Handle Failed Jobs In Laravel
  13. Best Ways To Define Global Variable In Laravel
  14. How To Get Latest Records In Laravel
  15. How To Break Nested Loops In PHP Or Laravel
  16. How To Pass Laravel URL Parameter
  17. Laravel Run Specific Migration
  18. Redirect By JavaScript With Example
  19. How To Schedule Tasks In Laravel With Example
  20. Laravel Collection Push() And Put() With Example

That’s it from our end. We hope this article helped you to learn the Laravel notification tutorial with example.

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you for reading this post 🙂 Keep Smiling! Happy Coding!

 
 

1 thought on “Laravel Notification Tutorial With Example”

Leave a Comment