phayes0289's avatar

Odd Issue Triggering a 404 in Postman.app, When Trying to Send Notification of New Data

I am in need of some help, as I am a bit over my head compared to my capabilities in object-oriented programming and Laravel.

I am attempting to send email and Web notifications for each new row of data being added to a model. This is the used for alerting firefighters to a new incident.

I actually have this for two different sets of code, one of which is working just fine. The first one decides which users it should send it to based on a user's alert preferences based on “Incident Type.” The second one is sent to users based on the unit assigned. There are two models for these notifications. The first is called “CadIncident” (table name=cad_incident). The second model is called CadIncidentVehicle (table name=cad_incidentvehicles) is related to the first one by the id field in “CadIncident”. There may be many rows for the vehicles (one for each vehicle) in the CadIncidentVehicle model, as many units are sent to a fire.

The CadIncident notifications are working fine, so I simply copied the code used and renamed classes as necessary. I then added the relationship as I need to return the CadIncident data with the unit notification.

I have a dummy incident created to test with. Using its “cadincident_id”, I am submitting data to the CadIncidentVehicle model through the API I have built using the Postman.app.

When I submit the JSON string via Postman.app, the data gets added to the model. There are no errors in the error log. But instead of getting a JSON string returned with the success status, I am getting a 404 error. If I remove the code from the model that triggers the notification code, I get the JSON success message. So I know the import API code is just fine.

I think it has something to do with how I am passing the CadIncident data, but to tell you the truth, that is a wild guess. I have no idea how to resolve or troubleshoot this. I am hoping I am just missing something obvious. Here is my code.

Here is my CadIncidentVehicle model that triggers the notification code:

class CadIncidentVehicle extends Model
{
    use HasFactory;
    protected $table = 'cad_incidentvehicles';
    protected $fillable = [
        'id',
        'cadincident_id',
        'vehicle_id',
        'vehicle_name',
        'time_assigned',
        'time_enroute',
        'time_arrived_on_scene',
        'time_staged',
        'time_contact',
        'time_call_cleared',
        'time_back_in_quaters',
        'cancel_reason',
        'location_when_assigned',
        'latitude_when_assigned',
        'longitude_when_assigned'
    ];

    public function CadIncident()
    {
        return $this->belongsTo(CadIncident::class, 'cadincident_id');  
    }

    protected static function booted()
    {
        static::created(function ($cadIncidentVehicle) {
            event(new CadIncidentVehicleCreated($cadIncidentVehicle->cadIncident, $cadIncidentVehicle));
        });
    }

Here is my CadIncidentVehicleCreated event:

class CadIncidentVehicleCreated
{
    use Dispatchable, SerializesModels;

    public $cadIncident;
    public $cadIncidentVehicle;

    Good Code
    public function __construct(CadIncident $cadIncident, CadIncidentVehicle $cadIncidentVehicle)
    {
        $this->cadIncident = $cadIncident;
        $this->cadIncidentVehicle = $cadIncidentVehicle;
    }
}

I have registered the event in the EventServiceProvider as follows:

protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],

        Login::class => [
            LoginListener::class,
        ],
        // Register the Event and Listener for sending the Alert Notification
        'App\Events\CadIncidentCreated' => [
            'App\Listeners\SendCadIncidentNotification',
        ],
        'App\Events\CadIncidentVehicleCreated' => [
            'App\Listeners\SendCadIncidentVehicleNotification',
        ],
    ];

This is my SendCadIncidentVehicleNotification Listener:

class SendCadIncidentVehicleNotification implements ShouldQueue
{
    use InteractsWithQueue;

    public function handle(CadIncidentVehicleCreated $event)
    {
        // Log the data from the newly created record
        $log = Log::channel('cad_incident_vehicle_notifications');
        $log->info('New CadIncident record created', [
            'id' => $event->cadIncident->id,
            'data' => $event->cadIncident->toArray(),
        ]);

        // Retrieve the incident type associated with the event
        $vehicle = $event->cadIncidentVehicle->vehicle_name;

        // Retrieve all users where useralert->name is equal to the $event->cadIncident->incidentType
        $users = User::whereHas('userAlerts', function ($query) use ($vehicle) {
            $query->where('notifier_id', $vehicle);
        })->get();

        // Retrieve all subscribed users    
        //$emailRecipients = User::where('id', '1')->get(); // Get recipients for email notifications
        // Send the notification to all subscribed users
        Notification::send($users, new NewCadIncidentVehicleEmail($event->cadIncident, $event->cadIncidentVehicle));

        // Retrieve all subscribed users
        // $subscribedUsers = PushSubscription::all(); // Assuming you want to notify all subscribed users
        $pushUsers = User::has('pushSubscriptions')
        ->whereHas('userAlerts', function ($query) use ($vehicle) {
            $query->where('notifier_id', $vehicle);
        })
        ->get();

        // Send the notification to subscribed users
        Notification::send($pushUsers, new NewCadIncidentVehiclePush($event->cadIncident, $event->cadIncidentVehicle));
    }
}

My code is throwing the 404 error sometime before the Listener gets involved. I know this becuase if I add a Die and Dump in the Listener function, it never gets triggered. The log never gets triggered, either.

What could be causing the 404 in Postman.app during the data insert instead of the API returning the normal JSON success string? I would appreciate any detailed instructions on how to troubleshoot this. I have been looking for a solution for two days.

0 likes
1 reply
LaryAI's avatar
Level 58

Based on the information provided, it seems that the 404 error is occurring before the event listener gets a chance to handle the event. This suggests that the issue might be related to the routing or the controller method that handles the API request, rather than the event and listener setup.

Here are some steps to troubleshoot the issue:

  1. Check the Route Definition: Ensure that the route handling the API request is correctly defined in your routes/api.php file. The route should point to the appropriate controller method that handles the creation of CadIncidentVehicle records.

  2. Inspect the Controller Method: Look at the controller method that is supposed to handle the request. Make sure that it is correctly creating the CadIncidentVehicle record and returning a JSON response upon success. If the record is being created successfully, the issue might be with the response or the route not being correctly matched after the record is created.

  3. Review the Model Event: Double-check the booted method in your CadIncidentVehicle model. Ensure that the event is being dispatched correctly. You might want to add some logging right before the event is dispatched to confirm that this part of the code is being executed.

  4. Check the Event and Listener Registration: Verify that the event and listener are registered correctly in your EventServiceProvider. The event class name and listener class name should be fully qualified and match the actual class names.

  5. Logging for Debugging: Add logging statements at various points in your controller method to see how far the request is getting before the 404 error occurs. Laravel's logging facilities can be used to write messages to the log:

    use Illuminate\Support\Facades\Log;
    
    // ...
    
    Log::info('Before creating CadIncidentVehicle');
    // Code to create the CadIncidentVehicle record
    Log::info('After creating CadIncidentVehicle');
    
  6. Check the API Response: Ensure that the controller method is returning a proper JSON response after the record is created. If you are using a form request or any other type of request validation, make sure it's not failing and causing a redirect (which could result in a 404 if the client is expecting a JSON response).

  7. Examine the .htaccess File: If you are using Apache, ensure that the .htaccess file is correctly configured to handle API requests and that mod_rewrite is enabled.

  8. Clear Caches: Sometimes, Laravel's route cache or configuration cache can cause unexpected behavior. Try clearing the caches using the following artisan commands:

    php artisan route:clear
    php artisan config:clear
    php artisan cache:clear
    
  9. Check the Network and Request Details: In Postman, inspect the network request and response details to ensure that the correct URL is being called and that the request is properly formed.

If after following these steps the issue persists, you may need to provide more specific details about the controller method handling the request, the exact route definition, and any middleware that might be affecting the request.

Please or to participate in this conversation.