Laravel Spark (Next) - Same Handle for multiple Events - laravel

Event listener that I am trying to perform the same action for 3 different Laravel Spark Next events.
Only the SubscriptionCreated seems to be triggered.
namespace App\Listeners;
use Spark\Events\SubscriptionCreated;
use Spark\Events\SubscriptionUpdated;
use Spark\Events\SubscriptionCancelled;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
class SparkSubscriptionUpdate
{
public function handle($event)
{
//do something;
}
public function subscribe($events)
{
return [
SubscriptionCreated::class => 'handle',
SubscriptionUpdated::class => 'handle',
SubscriptionCancelled::class => 'handle',
];
}
}
Can someone tell me if I am missing something?
Haven't been able to find any examples on the internet that this wouldn't work.

Related

lumen observer is not working on the eloquent model

I am using lumen 5.5. I am trying to make the observer called on while updating/deleting the model. When i tried that with user model, observer is not calling. When i did that with the events everything works fine. It's not even shows any errors.
Here is my code:
AppServiceProvider.php
....
use App\Models\User;
use App\Observers\UserObserver;
...
public function boot() {
User::observe(UserObserver::class);
}
App\Models\User.php
...
public static function changeCustomerStatus(int $customerID): int{
$customer = self::where([
'id' => $customerID,
'user_type' => app('config')->get('user_type.CUSTOMER')
])
->first();
if ($customer) {
$customer->status = $customer->status == app('config')->get('status.ACTIVE') ? app('config')->get('status.DEACTIVE') : app('config')->get('status.ACTIVE');
if ($customer->save()) {
return $customer->status;
}
return 0;
}
else
return 0;
}
...
App\Observers\UserObserver.php
<?php
namespace App\Observers;
use App\Models\User;
class UserObserver {
public function updated(User $user) {
if ($user->status === app('config')->get('status.DEACTIVE')) {
app('log')->info('updated');
}
}
public function saved(User $user) {
if ($user->status === app('config')->get('status.DEACTIVE')) {
app('log')->info('saved');
}
}
public function deleted(User $user) {
app('log')->info('deleted');
}
}
I even did the composer dump-autoload. But no luck
Lumen doesn't have observe feature.
You can use Events instead or make custom observer and call its functions from your code.
Read docs here - Events
Lumen does not have model observers the way Laravel does. I agree with using events or implementing your custom observers. If you choose to go with the latter, here is a post that might help.
https://link.medium.com/ZHsJwJuvC5

Laravel Guzzle not perforning any action as requested in Cron Job

I am developing a web application using Laravel-5.8. Also, I am using guzzlehttp/guzzle-6.3 to consume an external api and save it in my local database.
travelupdate.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp;
use GuzzleHttp\Client;
use App\User;
use App\Activity;
use Avatar;
use Storage;
use App\Travel;
class travelsupdate extends Command {
protected $signature = 'command:travelsupdate';
protected $description = 'travelsupdate';
public function __construct() {
parent::__construct();
}
public function handle()
{
$client = new Client();
$res = $client->request('GET','https://api.abcdef.net/travels/v4/sample');
$trips = json_decode($res->getBody(), true);
foreach($trips as $trip) {
Trip::updateOrCreate([
'trip_id' => $trip->trip_id
],
[
'trip_number' => $trip->trip_no,
'truck_no' => $trip->t_no,
'truck_reg_no' => $trip->reg_no,
'trailer_no' => $trip->trailer_no,
'contract_no' => $trip->contract_no,
'contract' => $trip->contract_name,
'driver_id' => $trip->driver_id,
'driver_name' => $trip->driver_name,
'loading_date' => date_format($trip->loading_date, "Y-m-d"),
'loading_from' => $trip->loading_from
]);
}
}
}
app\Console\Kernel.php
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\User;
use App\Activity;
use Avatar;
use Storage;
use Mail;
use App\Travel;
use App\Audit;
use Carbon\Carbon;
// use \Carbon\Carbon;
class Kernel extends ConsoleKernel
{
protected $commands = [
'App\Console\Commands\travelsupdate',
];
protected function schedule(Schedule $schedule)
{
$schedule->command('command:travelsupdate')
->hourly();
}
/**
* Register the commands for the application.
*
* #return void
*/
protected function commands()
{
// $this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
What I want to achieve is that consume the external api using Guzzle GET request. Then save it into the local database. If data already exists (using trip_id), it updates. I set the cron job to every one hour.
I observe that nothing is happening, and no data is being saved to the local database. When I tested on POSTMAN, it displays the data from the api.
However, Laravel log file is not showing me any error.
How do I resolve this?
NOTE: There is no security setting on the external api.
You are retreiving array from api and then you are using it as an object.
Solution 1:
do not decode it as an array
$trips = json_decode($res->getBody());
Solution 2:
use decoded value as an array
foreach($trips as $trip) {
Trip::updateOrCreate([
'trip_id' => $trip['trip_id']
],
[
'trip_number' => $trip['trip_no'],
'truck_no' => $trip['t_no'],
'truck_reg_no' => $trip['reg_no'],
'trailer_no' => $trip['trailer_no'],
'contract_no' => $trip['contract_no'],
'contract' => $trip['contract_name'],
'driver_id' => $trip['driver_id'],
'driver_name' => $trip['driver_name'],
'loading_date' => date_format($trip['loading_date'], "Y-m-d"),
'loading_from' => $trip['loading_from']
]);
}
Everything else seems to be ok.
If you want to display errors in your log you can do it manually:
try {
...
} catch (\Exception $e){
\Log::error($e->getMessage());
}
Not sure if you are misusing the terminology but you don't set the "cron job" for every hour. You set the "cron job" that calls the Laravel Scheduler to run every minute. The scheduler then decides every time it is ran what needs to be run based on how you setup the calls in the scheduler.
To test this you can adjust your scheduled command to run every minute or 5 minutes lets say and manually call the scheduler yourself, php artisan schedule:run, from the command line.

Dynamically hide Laravel barryvdh debugbar

I could not able to hide Laravel Debugbar dynamically, i.e on the run time. I have tried the following from parent Controller class constructor:
<?php
namespace App\Http\Controllers;
class Controller extends BaseController {
use AuthorizesRequests,
DispatchesJobs,
ValidatesRequests;
public $foo = 'null';
public function __construct() {
\Debugbar::disable();
// and also
config(['debugbar.enabled' => false]);
....
All of the above tries failed. I'd like to mention that controller is the parent controller of all other controllers' classes.
The only working way is not dynamic way, where I have to change configuration manually. I don't know why the override configurations doesn work as the documentation states?
Without seeing all you code, yours should work. Here is how I configure mine to work in a local environment and disable it with specific requests.
AppServiceProvider
use Barryvdh\Debugbar\ServiceProvider as DebugbarServiceProvider;
...
public function register()
{
if ($this->app->environment('local')) {
$this->app->register(DebugbarServiceProvider::class);
}
}
Where I would like to disable I put.
use Barryvdh\Debugbar\Facade as Debugbar;
...
if (App::environment('local')) {
Debugbar::disable();
}
Update per comment
Why do you put something in your routes file like this.
use Barryvdh\Debugbar\Facade as Debugbar;
...
Route::group(array('domain' => 'admin.example.com'), function()
{
Debugbar::disable();
});

Laravel events not firing?

I can't seem to get any of my eloquent.saved event handlers to run.
I tried this:
<?php
namespace App\Providers;
use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
protected $listen = [
'eloquent.saved: \App\Models\Company' => [
'\App\Models\Company#hasSaved',
],
];
}
And then added this method to \App\Models\Company:
public function hasSaved() {
die("SAVED!!!");
}
But it doesn't run when I save a company.
I tried creating an observer:
<?php
namespace App\Providers;
use App\Models\Company;
use App\Observers\CompanyObserver;
use DB;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register()
{
Company::observe(CompanyObserver::class);
}
}
But the events never fire:
<?php namespace App\Observers;
class CompanyObserver {
public function saved() {
die('saved');
}
public function saving() {
die('saving');
}
}
I tried using a listener class in EventServiceProvider instead:
protected $listen = [
'eloquent.saved: \App\Models\Company' => [
\App\Listeners\CompanySavedListener::class,
],
];
But that also never runs.
Lastly, I tried adding this to EventServiceProvider
public function boot(DispatcherContract $events)
{
parent::boot($events);
$events->listen('eloquent.*', function() {
dump(func_get_args());
});
}
And that does fire a bunch of random events, but it's just feeding me model instances -- I have no idea what events are actually firing.
So what's going on? I just want to know when my Company has saved.
Let's go for Observer way. The problem is that you used:
Company::observe(CompanyObserver::class);
in register method of AppServiceProvider and you should use it in boot method. When you move this line to boot method (of same class) it will work without a problem and when you save Company, code from saved method of CompanyObserver should be launched.

Trigger to Pusher.com does nothing

I am trying to use vinkla/pusher on Laravel 5.1
This is what I've added to app.php:
Vinkla\Pusher\PusherServiceProvider::class as a service provider
'LaravelPusher' => Vinkla\Pusher\Facades\Pusher::class, as a facade.
Route:
Route::get('/api/bid', [
'uses' => 'APIController#bid'
]);
And this is the controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\CurrentAuction;
use App\User;
use App\Bid;
use Session;
use LaravelPusher;
class APIController extends Controller
{
public function getCurrentAuction()
{
// snip...
}
public function bid(User $user) {
// Whole heap of things done with $user...
// snip...
$data['bids'] = 1;
LaravelPusher::trigger('bid_channel', 'NewBid', $data);
}
}
Calling that method does everything except trigger the pusher event.
I don't understand what I've done wrong.
Any help would be greatly appreciated. Thanks!
It appears that when using Laravel Homestead/Vagrant, pusher, broadcasting or anything like that doesn't want to work for me.
I pushed everything up to a live server and it worked without any code changes.

Resources