Log table creation using Laravel Events - laravel

I want to create a log each time when insertion happens to the files table. That is, everytime when an insertion to the files table happens, an event has to trigger to create a log for it automatically. Log table needs to have 3 columns id, fileid - primary key of files table & logDetails ,where the logDetails column store a msg like 1 file inserted.
i have read this - https://laravel.com/docs/8.x/events and also searched many more , but that couldn't help me to find where should i start. I have created an event page and a listeners page for this. But i don't know what to write in that.The below Controller & model does the insertion to the files table well. And where i need ur help is to code for creating a log for this insertion. Any help is much appreciated.
Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\FileLogs;
use Illuminate\Support\Facades\Validator;
use App\Events\InsertFileLog;
class FileLogController extends Controller
{
public function insert(Request $request) // insertion
{
$validator = Validator::make(
$request->all(),
[
'orderId' => 'required|integer', //id of orders table
'fileId' => 'required|integer', //id of file_type table
'status' => 'required|string'
]
);
if ($validator->fails()) {
return response()->json($validator->errors(), 400);
}
$obj = new FileLogs();
$obj->orderId=$request->orderId;
$obj->fileId=$request->fileId;
$obj->status=$request->status;
$obj->save();
//dd($obj->id);
if($obj->id!=''){
InsertFileLog::dispatch($order);
return response()->json(['status'=>'success','StatusCode'=> 200, 'message'=>'Successfully Inserted','data'=>$obj]);
}
else{
return response()->json(['status'=>'Failed','message'=>'Insertion Failed'],400);
}
}
Model
class FileLogs extends Model
{
use HasFactory;
use SoftDeletes;
protected $table='files';
protected $fillable = [
'orderId',
'fileId',
'status'
];
}
Event
<?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;
use App\Models\FileLogs;
class InsertFileLog
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $order;
public function __construct(FileLogs $order)
{
$this->order = $order;
}
}
Listener
<?php
namespace App\Listeners;
use App\Events\InsertFileLog;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use App\Models\Logs;
class FileLogListener
{
public function __construct()
{
//
}
public function handle(InsertFileLog $event)
{
//
}
}
EventServiceProvider.php
class EventServiceProvider extends ServiceProvider
{
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
];
public function boot()
{
//
}
}

The App\Providers\EventServiceProvider offers a way to register Events and Listeners. The key is the Event, the values are one or multiple Listeners. You should update your code to contain the following:
EventServiceProvider
class EventServiceProvider extends ServiceProvider
{
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
InsertFileLog::class => [
// Listeners in this array will be executed when InsertFileLog was fired.
FileLogListener::class
],
];
public function boot()
{
//
}
}
The FileLogListener will only be triggered after the event InsertFileLog was fired. To do that, you could do the following, by adding: InsertFileLog::dispatch($order); line before return success response in your insert function.
FileLogController
class FileLogController extends Controller
{
public function insert(Request $request) // insertion
{
$validator = Validator::make(
$request->all(),
[
'orderId' => 'required|integer', //id of orders table
'fileId' => 'required|integer', //id of file_type table
'status' => 'required|string'
]
);
if ($validator->fails()) {
return response()->json($validator->errors(), 400);
}
$obj = new FileLogs();
$obj->orderId=$request->orderId;
$obj->fileId=$request->fileId;
$obj->status=$request->status;
$obj->save();
//dd($obj->id);
if($obj->id!=''){
InsertFileLog::dispatch($obj);
// alternatively, the event helper can be used.
// event(new InsertFileLog($obj));
return response()->json(['status'=>'success','StatusCode'=> 200, 'message'=>'Successfully Inserted','data'=>$obj]);
}
else{
return response()->json(['status'=>'Failed','message'=>'Insertion Failed'],400);
}
}
}
FileLogListener
<?php
namespace App\Listeners;
use App\Events\InsertFileLog;
use App\Models\Log;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
class FileLogListener
{
public function __construct()
{
//
}
public function handle(InsertFileLog $event)
{
// $event->order contains the order.
// In your question, you have request an example of creating an insertion to the Log table
Log::create([
'fileId' => $event->order->fileId,
'logDetails' => '1 file inserted',
]);
}
}
Model observers
Alternatively, Model observers provide a solution without having to manually register events/listeners, as they listen to Eloquent events of the observed model like: creating, created, updated, deleted, etc.

Related

Larave 6 - pivot table sync - fire created event only if the attached user is new

I have following code:
$clinic->users()->sync($sync);
Which will go to this class (sync is working):
<?php
namespace App;
use Illuminate\Database\Eloquent\Relations\Pivot;
class ClinicUser extends Pivot
{
protected $table = 'clinic_user';
static function boot()
{
parent::boot();
static::created(function($item) {
$user = \App\User::find($item->users_id);
$clinic = \App\Models\Clinic::find($item->clinics_id);
if($user->userData->notification_email == 1)
\Mail::to($user->email)->send(new \App\Mail\ClinicManagerAdded(
$user,
$clinic));
if($user->userData->notification_app == 1)
\App\Notification::create([
'title' => "message",
'body' => "message",
'user_id' => $user->id,
]);
});
}
}
Is it possible to fire created method only to the new users (does which weren't detached)?
What i was suggesting is not that robust, infact you need to do
$clinic->users()->detach($sync->pluck('id'));
$clinic->users()->sync($sync);
Every time, and you need to remember it (and so is not robust).
What i feel to suggest you to do is something like this:
Delete the notification in the Model
Create a Service for this operation, let's call it NotyfyUsersNewClinicService (maybe you will find a better name):
<?php
namespace App;
use ...;
class NotyfyUsersNewClinicService{
public __constructor(){}
public updateUsers(Clinic& $clinic, Collection& $newUsers){
$clinic->users->diff($newUsers)->each(function(User $users){
$user->userData->notification_email = true;
\Mail::to($user->email)->send(new \App\Mail\ClinicManagerAdded(
$user,
$clinic));
});
$clinic->users()->sync($sync);
}
}
then you will only need to use this:
(new NotyfyUsersNewClinicService())->updateUsers($clinic, $users);
Note: better if you move the email to a job and send it using queue:work
If someone has a similar problem, I have managed to resolve this by creating the static variable, and fill this variable in the deleted event, like this:
<?php
namespace App;
use Illuminate\Database\Eloquent\Relations\Pivot;
class ClinicUser extends Pivot
{
protected $table = 'clinic_user';
static $ids = [];
static function boot()
{
parent::boot();
static::deleted(function($item){
self::$ids[] = $item->users_id;
});
static::created(function($item){
if(!\in_array($item->users_id, self::$ids)){
$user = \App\User::find($item->users_id);
$clinic = \App\Models\Clinic::find($item->clinics_id);
if($user->userData->notification_email == 1)
\Mail::to($user->email)->send(new \App\Mail\ClinicManagerAdded(
$user,
$clinic));
if($user->userData->notification_app == 1)
\App\Notification::create([
'title' => "new message",
'body' => "<p>body</p>",
'user_id' => $user->id,
]);
}
});
}
}

Pass variable from controller to notification in Laravel

I am finding it hard to understand the examples from the docs to the scenario I am having. In my project I have an application form which filled up by the user then admin will update that form once the application is approved, canceled etc.
Now I want to notify the user that her/his application has been approved, canceled etc.
in my controller:
public function update(Request $request, $id)
{
$this->validate($request, [
'status' => 'required'
]);
$requestData = $request->all();
$loanapplication = LoanApplication::findOrFail($id);
$loanapplication->update([
"status" => $request->status,
"admin_notes" => $request->admin_notes,
"date_approval" => $request->date_approved
]);
if($request->notifyBorrower = 'on') {
$user_id = $loanapplication->user_id;
$status = $request->status;
$this->notify(new AdminResponseToApplication($user_id));
}
return redirect()->back()->with('flash_message', 'LoanApplication updated!');
}
In my AdminResponseToApplication.php I like to achieve this
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
class AdminResponseToApplication extends Notification implements ShouldQueue
{
use Queueable;
public function __construct()
{
//
}
public function via($notifiable)
{
return ['mail','database'];
}
public function toMail($notifiable)
{
return (new MailMessage)
->line(.$user->nameHere. 'your application has been '.$statusHere.'.')
->action('check it out', url('/'))
->subject('Regarding with your loan application')
->line('This is system generated. Do not reply here.');
}
public function toDatabase($notifiable)
{
return [
'user_id' => $user->nameHere,
'status' => $statusHere,
'title' => .$user->nameHere. 'your application has been '.$statusHere.'.',
'url' => '/'
];
}
}
How can I achieve that? Thank you in advance!
Get user object and call function notify() on it. $this->notify() will not work because $this is not an instance of User class.
$user = User::find($user_id);
$user in the $user->notify(new AdminResponseToApplication($data)) function is available in notification class as $notifiable.
You can get any value of that object using $notifiable->name etc.
Remember:
AdminResponseToApplication is a class and you can do anything with it that a php class can.
So you can pass as many variables as you want to AdminResponseToApplication class in constructor and do what you want.
$user->notify(new AdminResponseToApplication($data))
As shown above I am sending a $data object to the class which is available in the constructor.
In the class
class AdminResponseToApplication extends notification implements ShouldQueue{
use Queueable;
public $myData;
public function __construct($data)
{
$this->myData = $data; //now you have a $data copied to $this->myData which
// you can call it using $this->myData in any function of this class.
}
}

How to Create Model with Notifiable Trait

I want create a Model with Notifiable feature,
First,in my controller :
$collection = collect([
[
'name' => 'user1',
'email' => 'user1#gmail.com',
],
[
'name' => 'user2',
'email' => 'user2#gmail.com',
],
[
'name' => 'user1000',
'email' => 'user1000#gmail.com',
],
]);
$u3 = new User3($collection);
when I return $u3->getEmailList(); , output is :
[{"name":"user1","email":"user1#gmail.com"},{"name":"user2","email":"user2#gmail.com"},{"name":"user1000","email":"user1000#gmail.com"}]
my class for User3 is:
namespace App;
use App\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Notification;
use Illuminate\Notifications\RoutesNotifications;
use Notifications\EmailClientOfAccount;
class User3 extends User
{
use Notifiable;
public $emailList;
public function __construct($emails)
{
$this->emailList = $emails;
}
public function getEmailList()
{
return $this->emailList;
}
public function routeNotificationForMail($notification)
{
return $this->emailList['email'];
}
}
Then, I pass $u3 to Notification as:
Notification::send($u3->getEmailList(), new
SendMailNotification($template,$subject,$request->input('mailFromTitle'),$attachments));
It show below error:
Symfony\Component\Debug\Exception\FatalThrowableError: Call to a member function routeNotificationFor() on array
can you help me for solve this problem,Please?
Thanks in Advance,
//-------------------
I correct to :
Notification::send($u3, new SendMailNotification($template,$subject,$request->input('mailFromTitle'),$attachments));
In my My Notification:
public function toMail($notifiable)
{
return new EmailTo($notifiable,$this->view,$this->topic,$this-
>mailFrom,$this->attaches);
}
and in Build():
public function build()
{
$email= $this->view($this->view);
return $email;
}
But it not work, I dont know where is mistake?
Notification send expects a Notifiable object, not the email list itself, if you change it to this, you should get further.
Notification::send($u3, new SendMailNotification($template,$subject,$request->input('mailFromTitle'),$attachments));

Map Eloquent event to a dedicated class in Laravel does not work

I am trying to catch in Laravel 5.5 the eloquent.created event when a Post model is created, but for any reason it does not work. It looks like the event/listener mapping that is defined inside the EventServiceProvider.php does not work. My setup is as follows.
EventServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
protected $listen = [
'App\Events\PostWasPublished' => [
'App\Listeners\NotifyBlogSubscribers',
]
];
public function boot()
{
parent::boot();
//
}
}
NotifyBlogSubscribers.php listener
<?php
namespace App\Listeners;
use App\Events\PostWasPublished;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class NotifyBlogSubscribers
{
public function __construct()
{
//
}
public function handle(PostWasPublished $event)
{
dd('Inside NotifyBlogSubscribers');
}
}
PostWasPublished.php
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class PostWasPublished
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public function __construct()
{
dd('Inside PostWasPublished');
}
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
}
Post.php
<?php
namespace App\Models;
use App\Events\PostWasPublished;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
class Post extends Model {
protected $events = [
'created' => PostWasPublished::class,
];
protected $fillable = ['user_id', 'title', 'body'];
public function comments() {
return $this->hasMany(Comment::class);
}
public function addComment($body) {
Comment::create([
'body' => $body,
'post_id' => $this->id
]);
}
public function user() {
return $this->belongsTo('App\User');
}
public function scopeFilter($query, $filters) {
if (array_key_exists('month', $filters)) {
$month = $filters['month'];
$query->whereMonth('created_at', Carbon::parse($month)->month);
}
if (array_key_exists('year', $filters)) {
$year = $filters['year'];
$query->whereYear('created_at', $year);
}
}
public static function archives() {
return static::selectRaw('year(created_at) as year, monthname(created_at) as month, count(*) published')
->groupBy('year', 'month')
->orderByRaw('min(created_at) desc')
->get()
->toArray();
}
public function tags() {
return $this->belongsToMany(Tag::class);
}
}
How do I test?
My first approach is to use tinker in the following way:
>>> App\Models\Post::create(['user_id' => '1', 'title' => 'some title', 'body' => 'lorem ipsum'])
=> App\Models\Post {#732
user_id: "1",
title: "some title",
body: "lorem ipsum",
updated_at: "2017-08-07 05:06:32",
created_at: "2017-08-07 05:06:32",
id: 62,
}
Also, when I create a post in the front-end it does not run into the dd() methods.
Also composer dump-autoload, php artisan clear-compiled or php artisan optimize did not do the trick. Any idea what I am doing wrong?
In Laravel 5.5 you will need to define a $dispatchesEvents property instead of a $events property. ($events was used in older Laravel versions).

Argument 1 passed to Illuminate\Auth\Guard::login() must implement interface Illuminate\Auth\UserInterface, null given open:

I have facebook login which uses socialite library. The error in the question occurs when the callback occurs.
Here is my "USER" model
<?php
namespace App;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
class User extends Model implements Authenticatable
{
//use Illuminate\Contracts\Auth\Authenticatable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
use \Illuminate\Auth\Authenticatable;
public function posts()
{
return $this->hasMany('App\Post');
}
public function likes()
{
return $this->hasMany('App\Like');
}
}
The Socialite logins are handled by SocialAuthController and what i understood from the error is , auth()->login($user); , null is passed to the login("NULL"). Here is the code of SocialAuthController. What's the mistake i have made here and how to fix this. thanks in advance
<?php
namespace App\Http\Controllers;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Socialite;
use App\SocialAccountService;
class SocialAuthController extends Controller
{
public function redirect($provider)
{
return Socialite::driver($provider)->redirect();
}
use \Illuminate\Auth\Authenticatable;
public function callback(SocialAccountService $service , $provider)
{
$user = $service->createOrGetUser(Socialite::driver($provider));
auth()->login($user);
return redirect()->to('/home');
}
}
The below is the handling service that will try to register user or log in if account already exists.
Here is the code of SocialAccountService.php
<?php
namespace App;
use Laravel\Socialite\Contracts\Provider;
class SocialAccountService
{
public function createOrGetUser(Provider $provider)
{
$providerUser = $provider->user();
$providerName = class_basename($provider);
$account = SocialAccount::whereProvider($providerName)
->whereProviderUserId($providerUser->getId())
->first();
if ($account) {
return $account->user;
} else {
$account = new SocialAccount([
'provider_user_id' => $providerUser->getId(),
'provider' => $providerName
]);
$user = User::whereEmail($providerUser->getEmail())->first();
if (!$user) {
$user = User::create([
'email' => $providerUser->getEmail(),
'name' => $providerUser->getName(),
]);
}
$account->user()->associate($user);
$account->save();
return $user;
}
}
}
This will try to find provider's account in the system and if it is not present it will create new user. This method will also try to associate social account with the email address in case that user already has an account.
My wild guess is that createOrGetUser() returns NULL because the SocialAccount does not have a user. So what could do is change the if condition in that method to check if the $account has a user:
public function createOrGetUser(Provider $provider)
{
...
if ( $account && property_exists($account, 'user') && $account->user ) {
return $account->user;
} else {
...

Resources