unioil-cms-fe/app/Livewire/Buttons/CreateNotification.php

71 lines
1.8 KiB
PHP

<?php
namespace App\Livewire\Buttons;
use Livewire\Component;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Session;
class CreateNotification extends Component
{
public $subject;
public $description;
public $set_schedule = 'no';
public $schedule;
public $expiration;
public $status = 0;
public function submit()
{
$token = Session::get('user')['access_token'] ?? null;
if (!$token) {
$this->addError('users', 'No access token found.');
return;
}
$response = Http::withToken($token)->post(config('services.backend_api.url') . '/api/cms/notification', [
//BE Expect request
'subject' => $this->subject,
'description' => $this->description,
'schedule' => $this->set_schedule === 'yes' ? $this->schedule : null,
'expiration' => $this->set_schedule === 'yes' ? $this->expiration : null,
'status' => $this->status,
]);
// dd($response);
//handle backend response
if ($response->status() === 422) {
$errors = $response->json('data');
foreach ($errors as $field => $messages) {
$this->addError($field, $messages[0]);
}
return;
}
if ($response->successful()) {
session()->flash('success', 'Notification created successfully.');
return redirect('/main/notification');
} else {
$this->addError('notification', 'Failed to create notification.');
}
}
public function cancel()
{
return redirect()->to('/main/notification');
}
public function render()
{
return view('livewire.buttons.create-notification');
}
}