File: /var/www/admin.fixgini.com/app/Http/Controllers/HeroController.php
<?php
namespace App\Http\Controllers;
use App\Models\Hero;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class HeroController extends Controller
{
public function index()
{
return view('banner.index');
}
public function list()
{
$heros = Hero::InRandomOrder()->limit(3)->get();
return response()->json(['status' => 'success', 'message' => 'Fetch successfully', 'data' => $heros]);
}
public function store(Request $request)
{
try {
$validatedData = $request->validate([
'title' => 'required|unique:heroes,title',
'subtitle' => 'nullable|unique:heroes,subtitle',
'banner_url' => 'sometimes|image|mimes:jpeg,png,jpg,gif|max:1025',
], [
'banner_url'=> 'The banner image is required',
]);
if ($request->hasFile('banner_url')) {
$uploadedFile = $request->file('banner_url')->getRealPath();
$uploadResult = cloudinary()->upload($uploadedFile, ['folder' => 'heroBanners']);
$uploadedFileUrl = $uploadResult->getSecurePath();
$publicId = $uploadResult->getPublicId();
}
$hero = Hero::create([
'title' => ucwords($validatedData['title']),
'subtitle' => ucfirst($validatedData['subtitle']),
'banner_url' => $uploadedFileUrl ?? NULL,
'banner_public_id' => $publicId ?? NULL,
]);
return response()->json(['status' => 'success', 'message' => 'Hero Banner created successfully', 'hero' => $hero], 200);
} catch (\Throwable $th) {
return response()->json(['status' => 'error', 'message' => $th->getMessage()], 400);
}
}
public function update(Request $request, $id)
{
try {
$validatedData = $request->validate([
'id' => 'required|exists:heroes,id',
'title' => 'required',
'subtitle' => 'nullable',
'banner_url' => 'sometimes|image|mimes:jpeg,png,jpg,gif|max:1025',
]);
$hero = Hero::findOrFail($id);
// If icon is uploaded, store it
if ($request->hasFile('banner_url')) {
$uploadedFile = $request->file('banner_url')->getRealPath();
$uploadResult = cloudinary()->upload($uploadedFile, ['folder' => 'heroBanners']);
$uploadedFileUrl = $uploadResult->getSecurePath();
$publicId = $uploadResult->getPublicId();
// Delete the old icon file and public ID if they exist
if ($hero->banner_public_id) {
cloudinary()->destroy($hero->banner_public_id);
}
} else {
$uploadedFileUrl = $hero->banner_url;
$publicId = $hero->banner_public_id;
}
$hero->update([
'title' => ucwords($validatedData['title']),
'subtitle' => ucfirst($validatedData['subtitle']),
'banner_url' => $uploadedFileUrl,
'banner_public_id' => $publicId,
]);
return response()->json(['status' => 'success', 'message' => 'Hero Banner updated successfully', 'hero' => $hero], 200);
} catch (\Throwable $th) {
return response()->json(['status' => 'error', 'message' => $th->getMessage()], 500);
}
}
public function supportMessages()
{
return view('support.index');
}
}