Event listener in laravel 5.4 - php

I am using laravel 5.4 for creating my project and i used auth controller for login and register what I need is to get the last login time of user and store it in database when i referred that i came about an idea of creating event listeners and i done it..
login event handling in laravel 5
This is in my
EventServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* #var array
*/
protected $listen = [
'App\Events\SomeEvent' => [
'App\Listeners\EventListener',
],
'Illuminate\Auth\Events\Login' => [
'App\Listeners\AuthLoginListener',
],
];
/**
* Register any events for your application.
*
* #return void
*/
public function boot()
{
parent::boot();
}
}
I defined listener as AuthLoginListner and my
> AuthLoginListner.php
<?php
namespace App\Listeners;
use Carbon\Carbon;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\User;
use Illuminate\Auth\Events\Login;
class AuthLoginListener
{
/**
* Create the event listener.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* #param auth.login $event
* #return void
*/
public function handle(Login $event)
{
return "yes";
}
}
Here i just return one text now what my doubt is how its working and where i get this yes message it doesnot show me any error now have an doubt its working correcty or not if yes where i get this message ..please any one help me out i just confused with this ...

Here is how I achieved it.
I created a new Listenener here App/Listeners/LogSuccessfullLogin.php
namespace App\Listeners;
use Illuminate\Auth\Events\Login;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use \Carbon\Carbon;
class LogSuccessfulLogin
{
/**
* Create the event listener.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* #param Login $event
* #return void
*/
public function handle(Login $event)
{
$event->user->last_login = Carbon::now();
$event->user->save();
}
}
and then in the EventServiceProvider, I observed for the Illuminate\Auth\Events\Login event as such:
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* #var array
*/
protected $listen = [
'Illuminate\Auth\Events\Login' => [
'App\Listeners\LogSuccessfulLogin',
]
];
/**
* Register any events for your application.
*
* #return void
*/
public function boot()
{
parent::boot();
//
}
}
So each time a user is logging in, it will save the timestamp in the last_login field in the users table.
Hope this helps!

Related

Laravel 5.5: Authorization Policy AccessDeniedHttpException This action is unauthorized

I created a policy for authorization, so I faced with this problem.
I have seen these solutions, but my problem didn't solve yet:
Solution 1
Solution 2
Solution 3
Here are the Codes:
Function used in ArticalesController Class:
public function show(Articale $articale)
{
$this->authorize('view', $articale);
return view('articales.show',compact('articale'));
}
ArticalePolicy Class:
<?php
namespace App\Policies;
use App\User;
use App\Articale;
use Illuminate\Auth\Access\HandlesAuthorization;
class ArticalePolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can view the articale.
*
* #param \App\User $user
* #param \App\Articale $articale
* #return mixed
*/
public function view(User $user, Articale $articale)
{
return $user->id == $articale->user_id;
}
AuthServiceProvider Class:
namespace App\Providers;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* #var array
*/
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
Articale::class => ArticalePolicy::class,
];
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
//
}
}
Try with your model name as like this replace it with your AuthServiceProvider
replace
Articale::class => ArticalePolicy::class,
with
'App\Articale' => 'App\Policies\ArticalePolicy',

Laravel listener not working, column not updating

I created a listener that updates a field in the database when a new user is created. THis is my event.
class NewUser
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $user;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Get the channels the event should broadcast on.
*
* #return Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
}
and my listener
public function handle(NewUser $event)
{
$captainrefid = DB::table('users')->where('referral_id', $event->user->referred_by)->value('referral_id');
$capdownlnrs = DB::table('users')->where('upliner', $captainrefid)->get();
if(count($capdownlnrs) > 2){
return DB::table('users')->where('id', $event->user->id)->update(['upliner' => $captainrefid]);
}
this is my event service provider
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as
ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* #var array
*/
protected $listen = [
'App\Events\NewUser' => [
'App\Listeners\UserPairingAndSpillover',
],
];
/**
* Register any events for your application.
*
* #return void
*/
public function boot()
{
parent::boot();
//
}
}
it is register in the user model.
protected $events = [
'created' => Events\NewUser::class
];
it does not give any error though. Yet the column us the database is not updating. Can anyone help me as to why? I do not have to queue it compulsorily.

Automatic login after clicking on the link with the token (jrean/laravel-user-verification)

I use the "jrean/laravel-user-verification" package. When I click on the link with the token I want to redirect in my homepage and be already logged. How can I implement this? Thank you)
Laravel: 5.4
Package Version: 4.1
Solve this problem. Add to my register function (RegisterController) event:
public function register(VerificationRequest $request)
{
...
event(new Registered($user));
...
}
Сreate listener:
<?php
namespace App\Listeners;
use Illuminate\Auth\AuthManager;
use Jrean\UserVerification\Events\UserVerified;
/**
* Class UserVerifiedListener
* #package App\Listeners
*/
class UserVerifiedListener
{
/**
* #var AuthManager
*/
private $auth;
/**
* Create the event listener.
*
* #param AuthManager $auth
*/
public function __construct(AuthManager $auth)
{
$this->auth = $auth;
}
/**
* Handle the event.
*
* #param UserVerified $event
* #return void
*/
public function handle(UserVerified $event)
{
$this->auth->guard()->login($event->user);
}
}
And register it in :
app/Providers/EventServiceProvider.php
<?php
namespace App\Providers;
use App\Listeners\UserVerifiedListener;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Jrean\UserVerification\Events\UserVerified;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* #var array
*/
protected $listen = [
UserVerified::class => [
UserVerifiedListener::class
],
];
/**
* Register any events for your application.
*
* #return void
*/
public function boot()
{
parent::boot();
//
}
public function register()
{
$this->app->bind(UserVerifiedListener::class, function () {
return new UserVerifiedListener(
$this->app->make('auth')
);
});
}
}

Event not firing Laravel 5.0.*

I am using Laravel 5.0.* and followed the following answer: login event handling in laravel 5 but I am still not able to see the event firing.
Anyone could help me with this:
This is how my Event Handler Class looks like:
<?php namespace App\Handlers\Events;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldBeQueued;
use App\User;
use Illuminate\Support\Facades\Log;
class AuthLoginEventHandler {
/**
* Create the event handler.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* #param User $user
* #param $remember
* #return void
*/
public function handle(User $user, $remember)
{
//
$user->login_counter = 1;
$user->save();
// $user->increment('login_counter');
Log::error('something wrong happened');
// dd("login fired and handled by class with User instance and remember variable");
}
}
And this is the EventServiceProvider:
<?php namespace App\Providers;
use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider {
/**
* The event handler mappings for the application.
*
* #var array
*/
protected $listen = [
'auth.login' => [
'App\Handlers\Events\AuthLoginEventHandler',
],
];
/**
* Register any other events for your application.
*
* #param \Illuminate\Contracts\Events\Dispatcher $events
* #return void
*/
public function boot(DispatcherContract $events)
{
parent::boot($events);
//
}
}
Appreciate your help
I use Laravel 5.2. I spent hours trying to figure out why my listener is not responding not knowing that I misspelled the event class name in the $listen array. Basically, if you fire your event like event(new SameEventClass(...)) make sure it is the same name you used in $listen => ['SameEventClass' => ['SameListener']]

Laravel 5 model event doesn't work (in production)

I've got saving model event in my EventServiceProvider.php
<?php namespace App\Providers;
use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use App\UnprotectedLead;
class EventServiceProvider extends ServiceProvider {
/**
* The event handler mappings for the application.
*
* #var array
*/
protected $listen = [
'event.name' => [
'EventListener',
],
];
/**
* Register any other events for your application.
*
* #param \Illuminate\Contracts\Events\Dispatcher $events
* #return void
*/
public function boot(DispatcherContract $events)
{
parent::boot($events);
UnprotectedLead::saving(function($lead)
{
dd($lead->lead_phone);
$lead->lead_phone_clean = preg_replace('/[^0-9]/', '', $lead->lead_phone);
});
}
}
This code work fine on localhost, but in production saving event does not work (I use dd() to check it in prod, but script didn't die)
How to debug this? Maybe EventServiceProvider.php didn't loaded in production?

Categories