78 lines
2.2 KiB
PHP
78 lines
2.2 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
declare(strict_types=1);
|
||
|
|
|
||
|
|
namespace App\Http\Controllers;
|
||
|
|
|
||
|
|
use App\Models\Documento;
|
||
|
|
use App\Models\Gruppo;
|
||
|
|
use Illuminate\Http\Request;
|
||
|
|
use Illuminate\Support\Facades\Storage;
|
||
|
|
|
||
|
|
class GruppoAvatarController extends Controller
|
||
|
|
{
|
||
|
|
public function store(Request $request, Gruppo $gruppo)
|
||
|
|
{
|
||
|
|
$this->authorizeWrite('gruppi');
|
||
|
|
|
||
|
|
$request->validate([
|
||
|
|
'avatar' => 'required|image|mimes:jpeg,png,gif,webp|max:2048',
|
||
|
|
]);
|
||
|
|
|
||
|
|
$existing = $gruppo->avatar;
|
||
|
|
if ($existing) {
|
||
|
|
if ($existing->file_path && Storage::disk('local')->exists($existing->file_path)) {
|
||
|
|
Storage::disk('local')->delete($existing->file_path);
|
||
|
|
}
|
||
|
|
$existing->delete();
|
||
|
|
}
|
||
|
|
|
||
|
|
$file = $request->file('avatar');
|
||
|
|
$path = $file->store('avatars/gruppi', 'local');
|
||
|
|
|
||
|
|
$documento = Documento::create([
|
||
|
|
'user_id' => auth()->id(),
|
||
|
|
'nome_file' => $file->getClientOriginalName(),
|
||
|
|
'file_path' => $path,
|
||
|
|
'tipologia' => 'avatar',
|
||
|
|
'visibilita' => 'gruppo',
|
||
|
|
'visibilita_target_id' => $gruppo->id,
|
||
|
|
'visibilita_target_type' => Gruppo::class,
|
||
|
|
'mime_type' => $file->getMimeType(),
|
||
|
|
'dimensione' => $file->getSize(),
|
||
|
|
]);
|
||
|
|
|
||
|
|
$gruppo->avatar()->save($documento);
|
||
|
|
|
||
|
|
return response()->json(['success' => true, 'avatar_url' => $documento->file_path]);
|
||
|
|
}
|
||
|
|
|
||
|
|
public function show(Gruppo $gruppo)
|
||
|
|
{
|
||
|
|
$this->authorizeRead('gruppi');
|
||
|
|
|
||
|
|
$avatar = $gruppo->avatar;
|
||
|
|
if (!$avatar || !$avatar->file_path || !Storage::disk('local')->exists($avatar->file_path)) {
|
||
|
|
abort(404);
|
||
|
|
}
|
||
|
|
|
||
|
|
$fullPath = Storage::disk('local')->path($avatar->file_path);
|
||
|
|
return response()->file($fullPath, ['Content-Type' => $avatar->mime_type]);
|
||
|
|
}
|
||
|
|
|
||
|
|
public function destroy(Gruppo $gruppo)
|
||
|
|
{
|
||
|
|
$this->authorizeWrite('gruppi');
|
||
|
|
|
||
|
|
$avatar = $gruppo->avatar;
|
||
|
|
if ($avatar) {
|
||
|
|
if ($avatar->file_path && Storage::disk('local')->exists($avatar->file_path)) {
|
||
|
|
Storage::disk('local')->delete($avatar->file_path);
|
||
|
|
}
|
||
|
|
$avatar->delete();
|
||
|
|
}
|
||
|
|
|
||
|
|
return response()->json(['success' => true]);
|
||
|
|
}
|
||
|
|
}
|