Sending Email in Laravel Using Gmail SMTP Using Event And Listener

                                        LARAVEL EVENT AND LISTENER



 Laravel's events provide a simple observer pattern implementation, allowing you to subscribe and listen for various events that occur within your application. Event classes are typically stored in the app/Events directory, while their listeners are stored in app/Listeners. Don't worry if you don't see these directories in your application as they will be created for you as you generate events and listeners using Artisan console commands.


Events serve as a great way to decouple various aspects of your application, since a single event can have multiple listeners that do not depend on each other. For example, you may wish to send a Slack notification to your user each time an order has shipped. Instead of coupling your order processing code to your Slack notification code, you can raise an App\Events\orderPlaced event which a listener can receive and use to dispatch a Slack notification.

    

Step1:

  Create  Event and Listener

Command:

 php artisan make:event orderPlaced

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class orderPlaced
{
use Dispatchable, InteractsWithSockets, SerializesModels;

/**
* Create a new event instance.
*
* @return void
*/
public $order;

public function __construct($order)
{
$this->order=$order;
}

/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
}


php artisan make:listener ordermail

1. Add Event (use App\Events\orderPlaced;)

<?php

namespace App\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use App\Models\OrderModel;
use App\Events\orderPlaced;
use App\Mail\Testmail;
use Illuminate\Support\Facades\Auth;
use Mail;
class orderMail
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}

/**
* Handle the event.
*
* @param object $event
* @return void
*/
public function handle(orderPlaced $event)
{
// dd($event);
// //dd(get_object_vars($event));
$data = array('name'=>"xxxx");
Mail::send('mail', $data, function($message) {
$message->to(Auth::user()->email, 'Tutorials Point')
->subject('subject')
->setBody('some body', 'text/html');
});
}
}

Step2:

   Create  OrderController and Model:

  php artisan make: Controller OrderController

<?php

namespace App\Http\Controllers;
use App\Models\OrderModel;
use App\Events\orderPlaced;
use Illuminate\Http\Request;

class OrderController extends Controller
{
//

public function index(){
return view("home");
}

public function store(Request $request){
$order=OrderModel::create([
'name'=>$request->name,
'Product_id'=>$request->Product_id,
'Product_name'=>$request->Product_name,
'Quantity'=>$request->Quantity,
]);
event(new orderPlaced($order));

if( $order){
return response()->json([
"class"=>"Success",
"Message"=>"Order details Send to Your Mail SucessFully"
]);
}
}
}


   php artisan make:Model orderModel


<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class OrderModel extends Model
{
use HasFactory;

public $table='order_deails';

public $fillable=['name','Product_id','Product_name','Quantity'];
}


Step3: Create table  for Order.Note(demo Table for reference)


CREATE TABLE `order_deails` (

  `id` int UNSIGNED NOT NULL,

  `name` varchar(255) NOT NULL,

  `Product_id` int NOT NULL,

  `Product_name` varchar(255) NOT NULL,

  `Quantity` int NOT NULL,

  `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,

  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP

) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;



Step4:  Route:

Route::any('/orderdata', [App\Http\Controllers\OrderController::class, 'store'])->name('orderdata');


Step5:

OrderPlacing Web Page html tag home.blade.php




@extends('layouts.app')

@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Dashboard') }}</div>

<div class="card-body">
@if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
@endif

{{ __('You are logged in!') }}

<div class="form-group">
<label for="Name">Name</label>
<input type="text" class="form-control cls_name" name="name" >
</div>
<div class="form-group " >
<meta name="csrf-token" content="{{ csrf_token() }}">
<label for="Name">Product_id</label>
<input type="number" class="form-control cls_product" name="Product_id" >
</div>
<div class="form-group">
<label for="Name">Product_name</label>
<input type="text" class="form-control cls_productname" name="Product_name" >
</div>
<div class="form-group">
<label for="Name">Quantity</label>
<input type="number" class="form-control cls_Quantity" name="Quantity" >
</div>
<button class="btn btn-primary order_details">Order</button>
<div>
</div>
</div>
</div>
</div>
</div>
<script>
$(".order_details").on('click',function(){

//console.log(form);
$.ajax({
url:"{{route('orderdata')}}",
method:"Post",
data:{
name:$(".cls_name").val(),
Product_id:$(".cls_product").val(),
Product_name:$(".cls_productname").val(),
Quantity:$(".cls_Quantity").val()
},
headers:{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success:function(data){
console.log(data);
}
});

});
</script>
@endsection




Step6: Registering Event and Listener in EventServiceProvider

App/Providers/EventServiceProvider.php

<?php

namespace App\Providers;

use App\Listeners\orderMail;

use App\Events\orderPlaced;

use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;


class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
newlyadded::class,
],
orderPlaced::class=>[
orderMail::class,
]

];

/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
//
}
}



Step7: resources/views/mail.blade.php


<h1>Hi, {{ $name }}</h1>
l<p>Sending Mail from Laravel.</p>


Step8: Configure Gmail in Env File:


MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=yyyyyyy@gmail.com
MAIL_PASSWORD=ybjffuuvxbbcxeks
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=xxxxxx@gmail.com
MAIL_FROM_NAME="${APP_NAME}"


Step9: Chrome  Account Mail Password Generate:

To Enable 2 Step verification:     https://myaccount.google.com/

Click->Security:



 Click->2 Step Verification:





Click->Click app Password  and Create App Password  to Connect Gmail to Project:




Create Password with your App Name:


Comments