Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

codercotton's avatar

Sending notification from Spark API POST

I'm trying to get a notification from my Spark app when a new 'session' is started (not web app session). It's currently saving the session object, but the notification->create gives an error on $user as noted below. I have a few issues I want to address, and would love a hint or three!

  1. My simple JSON POST should be able to save with a single command, but I had to manually assign each var to make it work. Whats the best practice method for a simple JSON POST via Spark API?
  2. I thought the $user should be automatically assigned as the api routes has the auth:api middleware, but $user doesn't work.
  3. I haven't actually gotten the notification to work yet, so I'm curious if anything else is required for that? I added the NotificationRepository to the use statements and assigned the $notifications variable in __construct() as in the docs.
public function store(Request $request)
{
    $session = new Session;
    $session->sid = $request->input('session.sid');
    $session->hostname = $request->input('session.hostname');
    $session->username = $request->input('session.username');
    $session->save();
    // send to redis -> socket.io -> browser vue instance
    event(new SessionReceived($session));
    $this->notifications->create($user, [                            <----------------- Undefined variable: user
        'icon' => 'fa-plus-square',
        'body' => $session->username.' started a session on '.$session->hostname.'.',
        'action_text' => 'View Session',
        'action_url' => '/sessions/'.$session->sid,
    ]);
}

My API route:

Route::group([
    'prefix' => 'api',
    'middleware' => 'auth:api'
], function () {
    Route::post('/session/{sid}', 'SessionController@store');
});

The simple JSON being POSTed:

{"session":{"sid":"Isssks","hostname":"host38","username":"cotton"}}

What would be the best practice for this simple JSON POST request with notification to a Spark API endpoint? TIA for any help you can give!

Cotton

0 likes
1 reply
codercotton's avatar
codercotton
OP
Best Answer
Level 8

This seems to work! The user was in $request->user().

public function store(Request $request)
{
    $session = new Session($request->all());
    $session->user_id = $request->user()->id;
    $session->save();
    // send to redis -> socket.io -> browser vue instance
    event(new SessionReceived($session));
    $this->notifications->create($request->user(), [
        'icon' => 'fa-plus-square',
        'body' => $session->username.' started a session on '.$session->hostname.'.',
        'action_text' => 'View Session',
        'action_url' => '/sessions/'.$session->sid,
    ]);
}
1 like

Please or to participate in this conversation.