share-lt/app/Http/Controllers/EntryController.php

94 lines
2.1 KiB
PHP
Raw Normal View History

<?php
namespace App\Http\Controllers;
use App\Http\Resources\EntryResource;
use App\Models\Entry;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
class EntryController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
return EntryResource::collection(Entry::with('category')->get());
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
$user = Auth::user();
if (! $user || $user->email !== config('app.admin_email')) {
return response()->json(['message' => 'Forbidden'], 403);
}
$validated = $request->validate([
'title' => 'required|string|max:255',
'content' => 'required|string',
]);
$validated['slug'] = $this->generateUniqueSlug($validated['title']);
return new EntryResource(Entry::create($validated));
}
private function generateUniqueSlug(string $title): string
{
do {
$slug = Str::slug($title).'-'.Str::random(8);
} while (Entry::where('slug', $slug)->exists());
return $slug;
}
/**
* Display the specified resource.
*/
public function show(Entry $entry)
{
$this->authorize('view', $entry);
return new EntryResource($entry);
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, Entry $entry)
{
$validated = $request->validate([
'title' => 'sometimes|required|string|max:255',
'content' => 'sometimes|required|string',
]);
$entry->update($validated);
return new EntryResource($entry);
}
/**
* Remove the specified resource from storage.
*/
public function destroy(Entry $entry)
{
$entry->delete();
return response()->noContent();
}
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return Auth::check();
}
}