-
routes/api.php
Open in GitHubuse App\Http\Controllers\Api\ArticleController; use Illuminate\Support\Facades\Route; Route::prefix('articles')->group( function () { Route::get('/', [ArticleController::class, 'index'])->middleware('api')->name('articles.index'); // }; // ); //
-
app/Http/Controllers/Api/ArticleController.php
Open in GitHubuse App\Http\Resources\ArticlesResource; use App\Models\Article; class ArticleController extends Controller { public function index(): ArticlesResource { $articles = Article::withcount( 'views', )->orderBy( 'created_at', 'DESC' )->take(50)->paginate(10); return new ArticlesResource($articles); } // }
-
app/Http/Resources/ArticlesResource.php
Open in GitHubuse Illuminate\Http\Resources\Json\ResourceCollection; class ArticlesResource extends ResourceCollection { public function toArray($request) { return [ 'data' => ArticleResource::collection($this->collection), ]; } }
-
app/Http/Resources/ArticleResource.php
Open in GitHubuse Illuminate\Http\Resources\Json\JsonResource; class ArticleResource extends JsonResource { public function toArray($request) { return [ 'type' => 'articles', 'id' => (string) $this->id, 'attributes' => [ 'id' => (string) $this->id, 'title' => $this->title, 'slug' => $this->slug, 'body' => $this->body, //\Str::words($this->body, 87, ''), 'votes' => $this->voters()->count(), 'upvotes' => $this->up ?? $this->upVoters()->count(), 'downvotes' => $this->down ?? $this->downVoters()->count(), 'views' => $this->views_count, 'created_at' => $this->created_at, 'is_up_voted' => auth()->guard('api')->id() ? auth()->guard('api')->user()->hasUpVoted($this->setAppends([])) : false, 'is_down_voted' => auth()->guard('api')->id() ? auth()->guard('api')->user()->hasDownVoted($this->setAppends([])) : false, 'real' => $this->num, ], 'relationships' => new ArticleRelationshipResource($this), 'links' => [ 'self' => route('articles.show', ['article_json' => $this->id]), ], ]; } // }