Code after event fire is not executing | Laravel 6 - laravel

I'm firing a status update event to broadcast on pusher. That's all working fine, however the code after the event fire doesnt work. At all.
Even if i put dd("hello"); nothing comes up. If i remove the event fire, things work as expected. I need this to work as i have a different redirect based on object parameter as shown below.
I can't figure out why this is happening, thanks for the help!
{
$room->start($connector);
event(new RoomStatusUpdated($room)); //problem here
if($room->autoLogin==1)
{
return redirect(route("room.join", $room->id));
}
else
{
notify()->info("","Meeting has started","bottomRight");
return back();
}
}

event(new RoomStatusUpdated($room)); //problem here
if your QUEUE_DRIVE=sync, Better you need to double check your event call as the event needs to be successful. Best practice is to include a temporary Logger by putting try-catch to your event
try{
//your event call
}catch(\Exception e){
Log::info("Code got excited: Line: {$e->getLine()} with error message: {$e->getMessage()}");
}
if queue driver is using a external like sqs or azure put back to sync first to trace back your event.

Related

Laravel: Where does report() store the error messages?

According to the Laravel handling error documentation I've put this code snippet in one of my functions:
try {
// Send an email...
} catch (Throwable $e) {
report($e);
return false;
}
Now I want to check out the error messages but I have no idea where they are stored.
I've tried both storage/logs/laravel.log and var/log/apache2/error.log but I found nothing.
Where does report() store the error message ?
It depends on your config/logging.php.
By default it should be the stack channel.
If your channel is set up to daily it willl create a file per day (e.g: laravel-2022-05-16.log
Otherwise you can leave the single channel it will put everything in storage/logs/laravel.log

Laravel 5.6 one event and many optional listeners

in Laravel 5.6
I have an event named DocumentSend,
And i have many Listeners Like (SendEmail, SendNotification, SendSMS),
listeners are optional (depends on document type and defined by user),
now the question is:
How can i call for example DocumentSend event with just SendSMS listener or DocumentSend with all the listeners?
I hope you get my mean,and tell me the best practice for my issue.
Thanks in advance
Well, the simple answers is - you can't. When you fire event all registered listeners will listen to this event and all of them will be launched.
However nothing stops you to prevent running code from listener.
For example you can fire event like this:
event(new DocumentSend($document, true, false, false));
and define constructor of DocumentSend like this:
public function __construct($document, $sendEmail, $sendNotification, $sendSms)
{
$this->document = $document;
$this->sendEmail = $sendEmail;
$this->sendNotification = $sendNotification;
$this->sendSms = $sendSms;
}
and now in each listener you can just verify correct variable, so for example in SendEmail listener in handle you can do it like this:
public function handle(DocumentSend $event)
{
if (!$event->sendSms) {
return;
}
// here your code for sending
}
similar you can do for other listeners.
Of course this is just example - you don't have to use 4 variables. You can set some properties to $document only to mark how it should be sent.

How to send a response from a method that is not the controller method?

I've got a Controller.php whose show($id) method is hit by a route.
public function show($id)
{
// fetch a couple attributes from the request ...
$this->checkEverythingIsOk($attributes);
// ... return the requested resource.
return $response;
}
Now, in checkEverythingIsOk(), I perform some validation and authorization stuff. These checks are common to several routes within the same controller, so I'd like to extract these checks and call the method everytime I need to perform the same operations.
The problem is, I'm unable to send some responses from this method:
private function checkEverythingIsOk($attributes)
{
if (checkSomething()) {
return response()->json('Something went wrong'); // this does not work - it will return, but the response won't be sent.
}
// more checks...
return response()->callAResponseMacro('Something else went wrong'); // does not work either.
dd($attributes); // this works.
abort(422); // this works too.
}
Note: Yes, I know in general one can use middleware or validation services to perform the checks before the request hits the controller, but I don't want to. I need to do it this way.
As of Laravel 5.6 you can now use for example response()->json([1])->send();.
There is no need for it to be the return value of a controller method.
Note that calling send() will not terminate the output. You may want to call exit; manually after send().
You are probably looking for this:
function checkEverythingIsOk() {
if (checkSomething()) {
return Response::json('Something went wrong');
}
if(checkSomethingElse()) {
return Response::someMacro('Something else is wrong')
}
return null; // all is fine
}
And in the controller method:
$response = $this->checkEverythingIsOk();
if($response !== null) { // $response instanceof Response
return $response;
}
It's probably overkill, but I will throw it in anyway. You might want to look into internal requests. Also this is just pseudoish code, I have not actually done this, so take this bit of information with caution.
// build a new request
$returnEarly = Request::create('/returnearly');
// dispatch the new request
app()->handle($newRequest);
// have a route set up to catch those
Route::get('/returnearly', ...);
Now you can have a Controller sitting at the end of that route and interpret the parameters, or you use multiple routes answered by multiple Controllers/Methods ... up to you, but the approach stays the same.
UPDATE
Ok I just tried that myself, creating a new request and dispatching that, it works this way. Problem is, the execution does not stop after the child-request has exited. It goes on in the parent request. Which makes this whole approach kind of useless.
But I was thinking about another way, why not throw an Exception and catch it in an appropriate place to return a specified response?
Turns out, thats already built into Laravel:
// create intended Response
$response = Response::create(''); // or use the response() helper
// throw it, it is a Illuminate\Http\Exception\HttpResponseException
$response->throwResponse();
Now usually an Exception would be logged and you if you are in Debug mode, you would see it on screen etc. etc. But if you take a look into \Illuminate\Foundation\Exceptions\Handler within the render method you can see that it inspects the thrown Exception if it is an instance of HttpResponseException. If it is then the Response will be returned immediately.
To me the most simple and elegant way is:
response()->json($messages_array, $status_code)->throwResponse();
(you don`t need return)
It can be called from a private function or another class...
I use this in a helper class to check for permissions, and if the user doesn`t have it I throw with the above code.

Logging all Events in Laravel 5.1 without hitting "nesting" exception

How can I log all Events in Laravel 5.1? I tried but get this error:
Maximum function nesting level of '100' reached
I have tried setting the xdebug nesting level to a higher value (900) with no luck.
Place the following in your EventServiceProvider's boot function. The key is to filter out "illuminate.log" events. If you don't filter those out, your logging statement will result in recursive evaluation of your Event handler.
Note that the Laravel framework seems to make extensive use of events for it's own purposes, so you will see lots of "internal" framework events listed in your log as well.
public function boot(DispatcherContract $events)
{
parent::boot($events);
Event::listen('*', function()
{
$event = Event::firing();
if(!starts_with($event, "illuminate.log")) {
Log::info("Event fired: " . $event . "\n");
}
});
}

How To Get Data From A Custom Event In Magento

I have an observer module that I have written for Magento. It simply monitors an event called mgd_order_prep which is triggered by a custom dispatcher like this:
Mage::dispatchEvent("mgd_order_prep", array('orderdata' => $order));
$order is simply a magento sales/order object.
My event fires and my function in the proper class executes:
function updateOrderPrepPDF($observer)
{
Mage::log("Update Order Prep",null,'orderprep.log');
Mage::log($observer->getOrderdata(),null,'orderprep.log');
}
I see what I should after the first log event, but I dont see ANYTHING for when I try to output the order data (it outputs blank - or null).
How do I get the data I pass in at the dispatch event out at the execution point?
You can directly get Data using getData() method :
function updateOrderPrepPDF($observer)
{
Mage::log(print_r($observer->getData(),true),null,'orderprep.log');
}
Check this log inside var/log directory.
Try this code and let me know if you still have any query.

Resources