Laravel 7/6 Notification Tutorial | Create Notification with Laravel 7/6 gửi mail đến phần 1 (ok)

https://www.itsolutionstuff.com/post/laravel-6-notification-tutorial-create-notification-with-laravel-6example.html

Mat khau moi: phamngoctuong1805@gmail.com lufcvcbdnbjcrvta

Ví dụ đã hoàn thành :

.env

APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:zGGputrJycx05I5m4LeL1wKuMm3N/tZlrjw0OaoZVug=
APP_DEBUG=true
APP_URL=http://localhost/test
LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=test
DB_USERNAME=root
DB_PASSWORD=
BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DRIVER=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=database
SESSION_LIFETIME=120
MEMCACHED_HOST=127.0.0.1
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=phamngoctuong1805@gmail.com
MAIL_PASSWORD=lufcvcbdnbjcrvta
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=phamngoctuong1805@gmail.com
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

C:\xampp\htdocs\blog\app\Notifications\MyFirstNotification.php

php artisan make:notification MyFirstNotification
<?php
   
namespace App\Notifications;
   
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
   
class MyFirstNotification extends Notification
{
    use Queueable;
  
    private $details;
   
    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($details)
    {
        $this->details = $details;
    }
   
    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail','database'];
    }
   
    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->greeting($this->details['greeting'])
                    ->line($this->details['body'])
                    ->action($this->details['actionText'], $this->details['actionURL'])
                    ->line($this->details['thanks']);
    }
  
    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toDatabase($notifiable)
    {
        return [
            'order_id' => $this->details['order_id']
        ];
    }
}

C:\xampp\htdocs\blog\routes\web.php

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| 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!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');
Route::get('send', 'HomeController@sendNotification');

C:\xampp\htdocs\blog\resources\views\welcome.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">

        <!-- Styles -->
        <style>
            html, body {
                background-color: #fff;
                color: #636b6f;
                font-family: 'Nunito', sans-serif;
                font-weight: 200;
                height: 100vh;
                margin: 0;
            }

            .full-height {
                height: 100vh;
            }

            .flex-center {
                align-items: center;
                display: flex;
                justify-content: center;
            }

            .position-ref {
                position: relative;
            }

            .top-right {
                position: absolute;
                right: 10px;
                top: 18px;
            }

            .content {
                text-align: center;
            }

            .title {
                font-size: 84px;
            }

            .links > a {
                color: #636b6f;
                padding: 0 25px;
                font-size: 13px;
                font-weight: 600;
                letter-spacing: .1rem;
                text-decoration: none;
                text-transform: uppercase;
            }

            .m-b-md {
                margin-bottom: 30px;
            }
        </style>
    </head>
    <body>
        <div class="flex-center position-ref full-height">
            @if (Route::has('login'))
                <div class="top-right links">
                    @auth
                        <a href="{{ url('/home') }}">Home</a>
                    @else
                        <a href="{{ route('login') }}">Login</a>

                        @if (Route::has('register'))
                            <a href="{{ route('register') }}">Register</a>
                        @endif
                    @endauth
                </div>
            @endif

            <div class="content">
                <div class="title m-b-md">
                    Laravel
                </div>

                <div class="links">
                    <a href="https://laravel.com/docs">Docs</a>
                    <a href="https://laracasts.com">Laracasts</a>
                    <a href="https://laravel-news.com">News</a>
                    <a href="https://blog.laravel.com">Blog</a>
                    <a href="https://nova.laravel.com">Nova</a>
                    <a href="https://forge.laravel.com">Forge</a>
                    <a href="https://vapor.laravel.com">Vapor</a>
                    <a href="https://github.com/laravel/laravel">GitHub</a>
                </div>
            </div>
        </div>
    </body>
</html>

C:\xampp\htdocs\blog\app\Http\Controllers\HomeController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\User;
use Notification;
use App\Notifications\MyFirstNotification;
  
class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }
  
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('home');
    }
  
    public function sendNotification()
    {
        $user = User::first();
        $details = [
            'greeting' => 'Hi Artisan',
            'body' => 'This is my first notification from ItSolutionStuff.com',
            'thanks' => 'Thank you for using ItSolutionStuff.com tuto!',
            'actionText' => 'View My Site',
            'actionURL' => url('/'),
            'order_id' => 101
        ];
        Notification::send($user, new MyFirstNotification($details));
        dd('done');
    }
}

Các bước cmd :)

  519 composer create-project --prefer-dist laravel/laravel blog
  520  cd blog/
  521  php artisan migrate
  522  history
  523  composer require laravel/ui
  524  php artisan list
  525  php artisan ui:auth
  526  php artisan notifications:table
  527  php artisan migrate
  528  php artisan make:notification MyFirstNotification

Laravel 7/6 Notification Tutorial | Create Notification with Laravel 7/6

By Hardik Savani | November 23, 2019 | Category : Laravel

Hi Guys,

In this tutorial, i will guide you how to send email notification in laravel 7/6. we will create laravel 7/6 notification to email address. we will send email to notify user using laravel 7/6 notification system.

Using laravel 6 notifications, you can send email, send sms, send slack message notification to user. in this example i give you very simple way to create first notification to send mail in laravel 6. we can easily create Notification by laravel artisan command. we can easily customization of notification like mail subject, mail body, main action etc. we almost require to use notification when we work on large amount of project like e-commerce. might be you need to send notification for payment receipt, order place receipt, invoice etc.

In this example we will create email notification and send it to particular user, than we saved to database. So, you need to follow few step to make basic example with notification.

Step 1: Install Laravel 6

I am going to explain step by step from scratch so, we need to get fresh Laravel 6 application using bellow command, So open your terminal OR command prompt and run bellow command:

composer create-project --prefer-dist laravel/laravel blog

Step 2: Create Database Table

In this step, we need to create "notifications" table by using laravel 5 artisan command, so let's run bellow command:

php artisan notifications:table
php artisan migrate

Read Also: Laravel 6 Generate PDF File Tutorial

Step 3: Create Notification

In this step, we need to create "Notification" by using laravel 5 artisan command, so let's run bellow command, we will create MyFirstNotification.

php artisan make:notification MyFirstNotification

now you can see new folder will create as "Notifications" in app folder. You need to make following changes as like bellow class.

app/Notifications/MyFirstNotification.php

<?php   namespace App\Notifications;   use Illuminate\Bus\Queueable;use Illuminate\Notifications\Notification;use Illuminate\Contracts\Queue\ShouldQueue;use Illuminate\Notifications\Messages\MailMessage;   class MyFirstNotification extends Notification{    use Queueable;      private $details;       /**     * Create a new notification instance.     *     * @return void     */    public function __construct($details)    {        $this->details = $details;    }       /**     * Get the notification's delivery channels.     *     * @param  mixed  $notifiable     * @return array     */    public function via($notifiable)    {        return ['mail','database'];    }       /**     * Get the mail representation of the notification.     *     * @param  mixed  $notifiable     * @return \Illuminate\Notifications\Messages\MailMessage     */    public function toMail($notifiable)    {        return (new MailMessage)                    ->greeting($this->details['greeting'])                    ->line($this->details['body'])                    ->action($this->details['actionText'], $this->details['actionURL'])                    ->line($this->details['thanks']);    }      /**     * Get the array representation of the notification.     *     * @param  mixed  $notifiable     * @return array     */    public function toDatabase($notifiable)    {        return [            'order_id' => $this->details['order_id']        ];    }}

Step 4: Create Route

In this is step we need to create routes for sending notification to one user. so open your "routes/web.php" file and add following route.

routes/web.php

Route::get('send', 'HomeController@sendNotification');

Step 4: Create Controller

Here,we require to create new controller HomeController that will manage generatePDF method of route. So let's put bellow code.

app/Http/Controllers/HomeController.php

<?php  namespace App\Http\Controllers;  use Illuminate\Http\Request;use App\User;use Notification;use App\Notifications\MyFirstNotification;  class HomeController extends Controller{    /**     * Create a new controller instance.     *     * @return void     */    public function __construct()    {        $this->middleware('auth');    }      /**     * Show the application dashboard.     *     * @return \Illuminate\Contracts\Support\Renderable     */    public function index()    {        return view('home');    }      public function sendNotification()    {        $user = User::first();          $details = [            'greeting' => 'Hi Artisan',            'body' => 'This is my first notification from ItSolutionStuff.com',            'thanks' => 'Thank you for using ItSolutionStuff.com tuto!',            'actionText' => 'View My Site',            'actionURL' => url('/'),            'order_id' => 101        ];          Notification::send($user, new MyFirstNotification($details));           dd('done');    }  }

Now we are ready to send first notification to user. so let's run our example so run bellow command for quick run:

php artisan serve

you can run following url:

http://localhost:8000/send

you can also send notification like this way:

$user->notify(new MyFirstNotification($details));

you can get sent notifications by following command:

Read Also: Laravel 7/6 Socialite Login with Google Gmail Account

dd($user->notifications);

I hope it can help you....

Last updated