72 lines
2.2 KiB
PHP
72 lines
2.2 KiB
PHP
<?php
|
|
namespace App\Http\Controllers\Api;
|
|
use App\Http\Controllers\Controller;
|
|
use App\Models\User;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Validation\Rule;
|
|
use Illuminate\Support\Facades\Storage;
|
|
|
|
class UserController extends Controller
|
|
{
|
|
public function index()
|
|
{
|
|
// Ambil pelanggan (bukan admin) dan paginasi
|
|
$users = User::with('profile') // <--- Tambahkan ini
|
|
->where('role', 'user')
|
|
->orderBy('created_at', 'desc')
|
|
->paginate(10);
|
|
|
|
// Kirim sebagai respons JSON
|
|
return response()->json($users);
|
|
}
|
|
|
|
public function show(string $id)
|
|
{
|
|
|
|
$user = User::with('profile')->findOrFail($id);
|
|
|
|
|
|
return response()->json($user);
|
|
}
|
|
|
|
public function update(Request $request, string $id)
|
|
{
|
|
$user = User::findOrFail($id);
|
|
|
|
$validatedData = $request->validate([
|
|
'name' => 'required|string|max:255',
|
|
'email' => ['required', 'string', 'email', 'max:255', Rule::unique('users')->ignore($user->id)],
|
|
'phone_number' => 'nullable|string|max:20',
|
|
'address' => 'nullable|string',
|
|
'customer_number' => 'nullable|string|max:50',
|
|
'status' => 'required|in:aktif,nonaktif',
|
|
'foto_profil' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048'
|
|
]);
|
|
|
|
$user->update([
|
|
'name' => $validatedData['name'],
|
|
'email' => $validatedData['email'],
|
|
'status' => $validatedData['status'],
|
|
]);
|
|
|
|
$profileData = [
|
|
'address' => $validatedData['address'] ?? null,
|
|
'phone_number' => $validatedData['phone_number'] ?? null,
|
|
'customer_number' => $validatedData['customer_number'] ?? null,
|
|
];
|
|
|
|
if ($request->hasFile('foto_profil')) {
|
|
if ($user->profile?->foto_profil) {
|
|
Storage::disk('public')->delete($user->profile->foto_profil);
|
|
}
|
|
|
|
$path = $request->file('foto_profil')->store('profil_images', 'public');
|
|
$profileData['foto_profil'] = $path;
|
|
}
|
|
|
|
$user->profile()->updateOrCreate(['user_id' => $user->id], $profileData);
|
|
|
|
return response()->json($user->load('profile'));
|
|
}
|
|
|
|
} |