axkuhta 1 rok temu
rodzic
commit
1311a94a86

+ 22 - 0
app/Http/Resources/AuthorResource.php

@@ -0,0 +1,22 @@
+<?php
+
+namespace App\Http\Resources;
+
+use Illuminate\Http\Request;
+use Illuminate\Http\Resources\Json\JsonResource;
+
+class AuthorResource extends JsonResource
+{
+    /**
+     * Transform the resource into an array.
+     *
+     * @return array<string, mixed>
+     */
+    public function toArray(Request $request): array
+    {
+        return [
+        	"id" => $this->id,
+			"name" => $this->name
+        ];
+    }
+}

+ 22 - 0
app/Http/Resources/BookResource.php

@@ -0,0 +1,22 @@
+<?php
+
+namespace App\Http\Resources;
+
+use Illuminate\Http\Request;
+use Illuminate\Http\Resources\Json\JsonResource;
+
+class BookResource extends JsonResource
+{
+    /**
+     * Transform the resource into an array.
+     *
+     * @return array<string, mixed>
+     */
+    public function toArray(Request $request): array
+    {
+        return [
+			"name" => $this->name,
+			"author_id" => $this->author->id
+        ];
+    }
+}

+ 6 - 0
routes/web.php

@@ -17,6 +17,8 @@ use Illuminate\Support\Facades\Route;
 Route::view('/', 'index');
 
 use App\Http\Controllers;
+use App\Http\Resources;
+use App\Models;
 
 // Книги
 Route::get('/books', [Controllers\BookController::class, 'index']);
@@ -37,3 +39,7 @@ Route::get('/author/{author}/edit', [Controllers\AuthorController::class, 'edit'
 Route::post('/author/{author}/edit', [Controllers\AuthorController::class, 'store']);
 Route::post('/author/{author}/comment', [Controllers\AuthorController::class, 'comment']);
 Route::post('/author/add', [Controllers\AuthorController::class, 'store']);
+
+// API
+Route::get('/api/authors', function() { return Resources\AuthorResource::collection(Models\Author::all()); });
+Route::get('/api/books', function() { return Resources\BookResource::collection(Models\Book::all()->load("author")); });