<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Image;
use App\Models\Images;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Yajra\DataTables\Facades\DataTables;
class UploadImagesController extends Controller
{
protected $database;
public function __construct()
{
$this->database = app('firebase.database');
}
public function index()
{
return view('admin.images.all');
}
public function add()
{
return view('admin.images.add');
}
public function listApi(Request $request)
{
if ($request->ajax()) {
$data = Image::all();
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function ($row) {
return '
<div class="">
<input class="delete_url" value="' . route("admin.images.delete", ["app_images", $row->images]) . '" hidden>
<a href="#" class="align-items-center btn btn-danger delete_btn">
<span class="icon icofont-pencil-alt-2"></span>
Delete
</a>
</div>';
})
->editColumn('images', function ($row) {
return '<img src="' . route("image", ["app_images", $row->images]) . '" height="50" loading="lazy">';
})
->rawColumns(['action'])
->make(true);
} else {
return 'lost';
}
}
public function store(Request $request)
{
$validateArray = [
'images' => 'required|array',
"images.*" => "required|string",
];
//validate
$validator = Validator::make($request->all(), $validateArray, ['images.*' => 'At least one image is required']);
if ($validator->fails()) {
return error_api_processor('Some fields seems not correct!', 200, validation_error_processor($validator));
}
try {
DB::beginTransaction();
$reference = $this->database->getReference('app_images');
$images = $reference->getValue();
for ($a = 0; $a < count($request->images); $a++) {
$image_name = get_base64_file($request->images[$a])['fileName'];
$image = Image::create([
'images' => $image_name,
]);
store_base64_file($request->images[$a], $image_name, 'app_images');
$images[] = $image_name;
}
$reference->set($images)->getKey();
DB::commit();
return success_api_processor($images, 'Image(s) added successfully.');
} catch (Exception $e) {
DB::rollBack();
return error_api_processor('Something went wrong! Please try again later.', 200, []);
}
}
public function delete($folder_name, $file_name): JsonResponse
{
$image = Image::where('images', $file_name)->first();
if ($image)
$image->delete();
try {
$reference = $this->database->getReference('app_images');
$images = $reference->getValue();
if (($key = array_search($file_name, $images)) !== false) {
unset($images[$key]);
}
$reference->set($images);
}catch (Exception $e){}
return delete_file($folder_name, $file_name);
}
}