unioil-cms-fe/app/Livewire/Promotion.php

65 lines
1.9 KiB
PHP

<?php
namespace App\Livewire;
use Livewire\Component;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Session;
use Livewire\Attributes\Layout; // Required for layout declaration
#[Layout('layouts.dashboard')] // Attribute syntax for Laravel 11
class Promotion extends Component
{
public $promotions = [];
public function mount()
{
$this->loadPromotions(); // Load users initially
}
public function loadPromotions()
{
try {
$token = Session::get('user')['access_token'] ?? null;
if (!$token) {
$this->addError('users', 'No access token found.');
return;
}
$response = Http::withToken($token)
->get(config('services.backend_api.url') . '/api/cms/promotion');
// dd($response->json());
if ($response->successful()) {
// Properly use collect to handle the response data
$this->promotions = collect($response->json()['data'])
->map(function ($promotions) {
return [
'promotion_uuid' => $promotions['promotion_uuid'],
'title' => $promotions['title'],
'type' => $promotions['promo_type']['name'],
'date_start' => $promotions['date_start'],
'date_end' => $promotions['date_end'],
'status' => $promotions['status'],
];
});
} else {
$this->addError('users', 'Failed to load promotions.');
}
} catch (\Exception $e) {
$this->addError('users', 'Error: ' . $e->getMessage());
}
}
public function render()
{
return view('livewire.promotion.promotion', [
'promotions' => $this->promotions,
]);
}
}