When i am registering user observer in Laravel while fetching single user also i'm getting list of all users - laravel

Getting issue with Laravel Observer
I created a user observer when i'm doing api call in order to fetch single user also i'm getting list of all user exist in table. what i'm doing wrong.
Here my ObserverProvider and UserObserver which i register in app.php
ObserversServiceProvider
namespace App\Providers;
use App\User;
use App\Observers\UserObserver;
use Illuminate\Support\ServiceProvider;
class ObserversServiceProvider extends ServiceProvider {
/**
* Bootstrap the application services.
*
* #return void
*/
public function boot() {
User::observe(UserObserver::class);
}
/**
* Register the application services.
*
* #return void
*/
public function register() {
}
}
UserObserver
namespace App\Observers;
use App\User;
class UserObserver
{
/**
* Listen to the User created event.
*
* #param User $user
* #return void
*/
public function created(User $user) {
// doing something
}
}
I'm getting list of all user when i'm doing.
$user = User::where('user_id',1)->first();

Related

Laravel 8.24 listeners/events doesn't adds to queue

I want to implement email notifications for some events. Also I was this events to be processed asynchronosly using Laravel database queue.
Here is what I have:
Event class:
<?php
namespace App\Events;
use App\Models\ServerReviewVote;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class NewServerReviewVote
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct(public ServerReviewVote $serverReviewVote)
{
}
}
Listener class:
<?php
namespace App\Listeners;
use App\Events\NewServerReviewVote;
use App\Notifications\NewServerReviewVote as NewServerReviewVoteNotification;
use Illuminate\Contracts\Queue\ShouldQueue;
class SendNewServerReviewVoteNotification implements ShouldQueue
{
/**
* Handle the event.
*
* #param NewServerReviewVote $event
* #return void
*/
public function handle(NewServerReviewVote $event)
{
$event->serverReviewVote->serverReview->author
->notify(new NewServerReviewVoteNotification($event->serverReviewVote->serverReview));
}
}
Notification class:
<?php
namespace App\Notifications;
use App\Models\ServerReview;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class NewServerReviewVote extends Notification implements ShouldQueue
{
use Queueable;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct(private ServerReview $serverReview)
{
}
/**
* Get the notification's delivery channels.
*
* #param User $notifiable
* #return array
*/
public function via(User $notifiable): array
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* #param User $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail(User $notifiable): MailMessage
{
return (new MailMessage)
->subject('New vote for your review!')
->greeting("Hello, {$notifiable->name}!")
->line("We got a new vote for your review for {$this->serverReview->server->name} server!")
->line("Your review currently have {$this->serverReview->votesUpCount()} upvotes and {$this->serverReview->votesDownCount()} downvotes.")
->line("Click the button below to navigate to the server page:")
->action($this->serverReview->server->name, route('servers.show', ['server' => $this->serverReview->server->slug]));
}
}
I'm firing event from this observer:
<?php
namespace App\Observers;
use App\Events\NewServerReviewVote;
use App\Models\ServerReviewVote;
class ServerReviewVoteObserver
{
/**
* #param ServerReviewVote $serverReviewVote
*/
public static function created(ServerReviewVote $serverReviewVote)
{
event(new NewServerReviewVote($serverReviewVote));
}
}
I configured queue database driver and my database has jobs table.
My expectations is that this event will be added to this table and than I can process it by using php artisan queue:work. But for some reason email sends synchronously instead of adding to queue. What have I missed?
Ok, I've been trying different ways and found how to make listeners to be added to queue.
I added public $connection = 'database' property to listener class.
Here is how it looks now:
<?php
namespace App\Listeners;
use App\Events\NewServerReviewVote;
use App\Notifications\NewServerReviewVote as NewServerReviewVoteNotification;
use Illuminate\Contracts\Queue\ShouldQueue;
class SendNewServerReviewVoteNotification implements ShouldQueue
{
/**
* Connection for queue
* #var string
*/
public string $connection = 'database';
/**
* Handle the event.
*
* #param NewServerReviewVote $event
* #return void
*/
public function handle(NewServerReviewVote $event)
{
$event->serverReviewVote->serverReview->author
->notify(new NewServerReviewVoteNotification($event->serverReviewVote->serverReview));
}
}
As far as I understood from Laravel docs this property isn't required but for some reason listener didn't dispatch to queue without it. Now it works good!
Also I cleared notification class as it doesn't need to implement ShouldQueue interface and use Queueable trait.
Here is how it looks now:
<?php
namespace App\Notifications;
use App\Models\ServerReview;
use App\Models\User;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class NewServerReviewVote extends Notification
{
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct(private ServerReview $serverReview)
{
}
/**
* Get the notification's delivery channels.
*
* #param User $notifiable
* #return array
*/
public function via(User $notifiable): array
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* #param User $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail(User $notifiable): MailMessage
{
return (new MailMessage)
->subject('New vote for your review!')
->greeting("Hello, {$notifiable->name}!")
->line("We got a new vote for your review for {$this->serverReview->server->name} server!")
->line("Your review currently have {$this->serverReview->votesUpCount()} upvotes and {$this->serverReview->votesDownCount()} downvotes.")
->line("Click the button below to navigate to the server page:")
->action($this->serverReview->server->name, route('servers.show', ['server' => $this->serverReview->server->slug]));
}
}
Now listener successfully dispatching to jobs table and can be processed by running php artisan queue:work database

Where is a "global bootstrap place" in Laravel

I am trying to install kylekatarnls/business-day package into Laravel 6. The docs say to "First load the mixin in some global bootstrap place of your app:". Where do I put this code?
One option is to place this in the boot method of your AppServiceProvider.
<?php
namespace App\Providers;
use Cmixin\BusinessDay;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* #return void
*/
public function register()
{
}
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
$additional_holidays = [
// ...
];
BusinessDay::enable(\Illuminate\Support\Carbon::class, 'us-national', $additional_holidays);
}
}
Another option is to create your own Service Provider and place the code in the new service provider's boot method.

I can fire events from Pusher debug console, but Laravel 5.2 isn't firing them

I am able to fire dummy events from the Pusher debug console and my client side is able to pick them up. But when I try to fire the event from my UserController nothing seems to happen.
Here is my Event class
<?php
namespace App\Events;
use App\Events\Event;
use App\Player;
use App\Product;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class NewPurchase extends Event implements ShouldBroadcast
{
use SerializesModels;
public $product;
/**
* Create a new event instance.
*
* #param Product $product
* #return void
*/
public function __construct(Product $product)
{
$this->product = $product;
}
/**
* Get the channels the event should be broadcast on.
*
* #return array
*/
public function broadcastOn()
{
return [Player::where('user_id', $this->product->seller_id)->first()->group_id];
}
}
Here is my listener, which doesn't have anything because I want everything to be process client side
<?php
namespace App\Listeners;
use App\Events\NewPurchase;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class NewPurchaseListener implements ShouldQueue
{
/**
* Create the event listener.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* #param NewPurchase $event
* #return void
*/
public function handle(NewPurchase $event)
{
//
}
}
Here is my .env
BROADCAST_DRIVER=pusher
PUSHER_APP_ID=858577
PUSHER_APP_KEY=ec160cc0a1ca15e463f4
PUSHER_APP_SECRET=
QUEUE_DRIVER=sync
Here is my event service provider
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* #var array
*/
protected $listen = [
'App\Events\NewPurchase' => [
'App\Listeners\NewPurchaseListener',
],
];
And here is where the event is fired
Event::fire(new NewPurchase($product));
My issue was that my version of Laravel hadn't been updated from the previous developers. Therefore the version of Pusher I had wasn't compatible at first with the version of Laravel I was using. I have tweaked this now and it works.

How to bind Services in Laravel?

Suppose I have a service: App\Services\FooService.
To use this service I need to bind it using this statement:
$this->app->bind('FooService', \App\Services\FooService::class);
So where do I need to put the above statement? In which file?
you need to bind in AppServiceProvider
app/Providers/AppServiceProvider.php
namespace App\Providers;
use App\SocialProvider;
use App\TwitterSocialProvider;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
$this->app->bind('FooService', \App\Services\FooService::class);
}
}

Laravel 5.3 Call to a member function groupBy() on null

I'm getting the following error:
FatalErrorException in EloquentVehicle.php line 30: Call to a member
function groupBy() on null
I have the following code:
<?php
namespace App\Project\Frontend\Repo\Vehicle;
use Illuminate\Database\Eloquent\Model;
class EloquentVehicle implements VehicleInterface
{
protected $vehicle;
/**
* EloquentVehicle constructor.
*
* #param Model $vehicle
*/
public function __construct(
Model $vehicle
)
{
$this->$vehicle = $vehicle;
}
/**
* Fetch unique makes
*
* #return mixed
*/
public function fetchMakes()
{
return $this->vehicle->groupBy(array('make'))
->orderBy('make', 'asc')
->get();
}
}
I've checked Illuminate\Database\Eloquent\Model for the method which is obviously not there, but I don't know what I should be adding to my class so that I can use the groupBy method. The laravel docs say the method exists.
UPDATE: Apparently I can't typehint an abstract class. I don't know how else I should be going about using Eloquent to retrieve records. If it helps, below is the code I have for registering the classes to the service container
<?php
namespace App\Providers;
use App\Vehicle;
use App\Project\Frontend\Repo\Vehicle\EloquentVehicle;
use Illuminate\Support\ServiceProvider;
class RepoServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* #return void
*/
public function boot()
{
//
}
/**
* Register the application services.
*
* #return void
*/
public function register()
{
$this->app->bind('App\Project\Frontend\Repo\Vehicle\VehicleInterface', function($app)
{
return new EloquentVehicle(
new Vehicle
);
});
}
}
I just found my mistake and quite literally lay my face in my palms.
This
$this->$vehicle = $vehicle;
should be this
$this->vehicle = $vehicle;

Resources