how to create job and event i n laravel , how to execute using logs, pusher method

 




how to create job

how to execute event

how to export the data

how to import the data

most advanced tops

laravel application not only executing htptp requests it is also capable of queue emthosds

when an event occurs

we wil lcall one job 

means it registration happens 

we will an event and excutes job

envent -> listen event, execute job or acation

php artisan make:job name

php artisan make:event event name


job is synchronois means when registration happens immediatel it will send email 

QUEUE_CONNECTION=sync

QUEUE_CONNECTION=sqs

QUEUE_CONNECTION=database

we have to run this using queue:listen

config/queue.php

sync => it will execut job immediately

'database' => [
'driver' => 'database',
'table' => 'jobs',
'queue' => 'default',
'retry_after' => 90,
'after_commit' => false,
],

sqs means it will execute to aws sqs server

MAIL_MAILER=log



$details = [
'title' => "Mail",
'password'=>$request->mobile,
'subject' => 'Heres Your Login Credentials',
'email' => $request->email,
'mail_type' =>'dummyMaillableTemplate',
'username'=> $request->name,
'url' => route('admin_login'),
];
Bus::dispatch(new SEJ($details));

at registration i will cal ljob it will using bus it will disp[atch

Bus::dispatch(new SEJ($details));
or

dispatch(new SEJ($details));

executin gjob or storing into jobs table 

once executed by php artisan queue:listen or php artisan queue:listen --quee=name 

php artisan queue:work

below ist companies job dispatched with queue name 

then 

(new CompaniesImport(($data->Company ?? ""), $data->batchData))->queue($file)->allOnQueue('excel-import');
Bus::batch([
new ProcessSites(($data->Sites ?? ""), $file),
new ProcessContacts(($data->Contacts ?? ""), $file),
new ProcessContactNumbers(($data->Contact_Numbers ?? ""), $file)
])->name($name)->onQueue('bus-excel-import')->then(function (Batch $batch) use ($data) {
$user = User::find($data->batchData->user);
$user_parts = str_replace("|", ".", $user->sub);
event(new Test([
"title" => 'Data Manager',
"subtitle" => 'Batch uploaded successfully',
"type" => 'light-success'
], $user_parts));
})->dispatch();


php artisan queue:listen --queue=excel-import

php artisan queue:listen --queue=bus-excel-import

php artisan queue:listen --queue=excel-import


For testing purposes, run the below command from the terminal.
Note: This same command is running from the Front end when a file is Uploaded from Data Overview section


php artisan import:batch '{"batchData":{"batch_id":"VAMSI-89589","sector_id":6,"provider_id":2,"user":3,"user_name":"testing","licensed_until":"2023-12-30 10:31:28"},"Company":["business_name","reg","company_type","website","headcount","est_turnover","sic","sic_description"],"Sites":{"0":"business_name","14":"address1","15":"address2","16":"address3","17":"town","18":"city","19":"county","20":"locality","21":"postcode"},"Contacts":{"0":"business_name","9":"title","10":"forename","11":"surname","12":"position","13":"email"},"Contact_Numbers":{"8":"number","13":"email"}}' /var/www/html/storage/app/public/files/vkguptha.xlsx

 


php artisan queue:listen --queue=excel-import

Note: It is executing the data from the jobs table and it reflects the companies table.


php artisan queue:listen --queue=bus-excel-import

Note: It is executing the data from job_batches  table and it reflects the jobs table 


php artisan queue:listen --queue=excel-import

Note: It is executing the data from jobs  table and it reflects the contacts, contact_numbers, sites table 


php artisan dummy:testing-command

Note: This is for developers testing purpose only, not for any user application.

It is clearing the columns where we executed with previous three commands. In that file we have to specify from  which date we have to clear.



exeute command from code 

$process = Process::fromShellCommandline("php ../artisan import:batch \"" . addslashes($config) . "\" " . Storage::disk('local')->path($fileData['path']));
$process->run();


send email job

<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Mail\MaillableTemplate;
use Mail;
class SendEmailJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $details;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($details)
{
$this->details = $details;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$myccEmail=env('CC_MAIL');
$mybccEmail =env('BCC_MAIL');
$mail= Mail::to($this->details['email'])->cc($myccEmail)->bcc($mybccEmail);
$mail->send(new MaillableTemplate($this->details));
}
}

====


maillabletemplate 

<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class MaillableTemplate extends Mailable
{
use Queueable, SerializesModels;
public $details;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($details)
{
$this->details = $details;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
// $template = 'emails.demoMail';
if ($this->details){
$template = 'emails.'.$this->details['mail_type'];
} else {
$template ='emails.demoMail';
}
return $this->markdown($template)
->subject($this->details['subject'])
->with('details', $this->details);
}

}

==

dummymaillabletemplate.blade.php

resources/views/emails/dummymaillabletemplate.blade.php

@component('mail::message')

<h2>Welcome to Our Platform!</h2>
<p>Dear {{ $details["username"] }},</p>
<p>Congratulations! Your account has been successfully created. Below are your login details:</p>
<p><strong>Email:</strong> {{ $details['email'] }}</p>
<p><strong>Password:</strong>{{ $details['password'] }}</p>
<p>We recommend that you change your password after your first login for security reasons.</p>
<p>Thank you for joining our platform. If you have any questions or need assistance, feel free to contact us.</p>
<p>Best regards,<br>Your Company Name</p>
@component('mail::button', ['url' => $details['url']])
Click here to login
@endcomponent

Thanks,<br>
{{ config('app.name') }}
@endcomponent

===

autcontroller calls jobs

job callls mail template 

it uses some html code

event 


in events three 

ist is calling event

next is taking data inevents

third is listenres what action hav to implament

if there is no migrations fo rqueue 

use php artisan queue:table

php artisan migrate

events

use import ht event

use app/events/myevent

event(new MyEvent(['key'=>'value')); => call this event


<?php

namespace App\Events;

use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class MyEvent
{
use Dispatchable, SerializesModels;

public $data;

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

registration at eventserviceprovider

protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
'App\Events\MyEvent' => [
'App\Listeners\MyEventListener',
],
];


<?php

namespace App\Listeners;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Events\MyEvent;

class MyEventListener implements ShouldQueue
{
public function handle(MyEvent $event)
{
// Handle the event, e.g., log it or perform some action
// sleep(50);
\Log::info('Event received with data: ' . json_encode($event->data));
}
}


==

php artisan make:event MyEvent
2004 php artisan make:listener MyEventListener --event=MyEvent
php artisan queue:table

php artisan queue:flush
php artisan queue:work database --queue=default^C

php artisan queue:work database --queue=default

executing jobs in queue with from database with queuename default


we can send to pusher or websockets using broadcast

sendint to pusher


<?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 NotificationEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;

public $data;

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

public function broadcastOn()
{
return new Channel('notification-channel');
}

// // Optionally, if you want to specify a queue for broadcasting
// public function broadcastQueue()
// {
// return 'notification-event';
// }

// public function broadcastAs()
// {
// return 'notification-event';
// }
}

==

registring events, calling event, calling listenerer, call to broadcast

composer  "pusher/pusher-php-server": "^7.2"

<?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 LogActivity implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;

public $data;

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

public function broadcastOn()
{
return new Channel('vamsi-channel');
}
}

=

pusher app credentials 

PUSHER_APP_ID=1717085
PUSHER_APP_KEY=c2b0e62ed3219b9e1afs
PUSHER_APP_SECRET=8d08435eb6800af67b68

PUSHER_APP_CLUSTER=ap2
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

listen that pusher events

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pusher Test</title>
</head>
<body>
<h1>Pusher Test</h1>
<p>
Publish an event to channel <code>vamsi-channel</code>
with event name <code>log-activity</code>; it will appear below:
</p>
<div id="app">
<ul>
<li v-for="message in messages">
{{ message }}
</li>
</ul>
</div>

<script src="https://js.pusher.com/8.2.0/pusher.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script>
// Enable pusher logging - don't include this in production
Pusher.logToConsole = true;

var pusher = new Pusher('c2b0e62ed3219b9e1afs', {
cluster: 'ap2',
encrypted: true,
});

var channel = pusher.subscribe('vamsi-channel');
channel.bind('log-activity', function (data) {
console.log('va',data);
app.messages.push(JSON.stringify(data));
});

// Vue application
const app = new Vue({
el: '#app',
data: {
messages: [],
},
});
</script>
</body>
</html>


==

 





 

=====

=


====

No comments:

Post a Comment

Event listening in react

 How we can listen to som eevents some envents fire like click or automatically user enters into input button , that is event on word type i...