Update post to also include its user

main
TZGyn 2 years ago
parent 8b166adc4f
commit 0c9f436432
Signed by: TZGyn
GPG Key ID: 122EAF77AE81FD4A

@ -14,15 +14,25 @@ class PostController extends Controller
$request->validate(
[
'lastPost' => 'required|integer',
'firstPost' => 'required|integer',
'order' => 'required|string|in:new,old',
]
);
$lastPost = $request->lastPost;
$firstPost = $request->firstPost;
$posts = Post::query()
->where(column: 'sequence', operator: '>', value: $lastPost)
->take(10)
->get();
$postsQuery = Post::query()->with('user')->orderByDesc(column: 'sequence');
if ($request->order == 'new') {
$postsQuery->where(column: 'sequence', operator: '>', value: $firstPost);
}
if ($request->order == 'old' && $lastPost != 0) {
$postsQuery->where(column: 'sequence', operator: '<', value: $lastPost);
}
$posts = $postsQuery->take(10)->get();
return response(
[

@ -5,10 +5,16 @@ namespace App\Models;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Post extends Model
{
use HasFactory, HasUuids;
protected $fillable = ['title', 'description'];
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}

@ -1,7 +1,11 @@
<script setup lang="ts">
type Post = {
user: {
name: String
}
title: String
description: String
created_at: string
}
const props = defineProps<Post>()
@ -10,6 +14,15 @@ const props = defineProps<Post>()
<template>
<div>
<div class="flex w-full flex-col gap-6 rounded-md border border-lightgray bg-secondary p-6">
<div class="flex justify-between">
<div class="flex h-full gap-4">
<Icon name="user" />
{{ props.user.name }}
</div>
<div>
{{ new Date(props.created_at).toLocaleString() }}
</div>
</div>
<div class="h-full truncate text-xl font-bold">
{{ props.title }}
</div>

@ -5,8 +5,11 @@ const PostValidator = z.object({
id: z.string(),
title: z.string(),
description: z.string(),
created_at: z.string(),
created_at: z.string().datetime(),
updated_at: z.string(),
user: z.object({
name: z.string(),
}),
})
const newPostValidator = z.object({

@ -27,9 +27,10 @@ onMounted(() => {
<div>
<Header />
<div class="mt-16 flex w-full items-center justify-center">
<div class="flex w-full max-w-2xl flex-col gap-4 px-4 pb-10 pt-4">
<div class="flex w-full max-w-2xl flex-col gap-4 px-4 pb-16 pt-4">
<div v-if="posts" v-for="post in posts">
<PostCard :title="post.title" :description="post.description" />
<PostCard :title="post.title" :description="post.description" :created_at="post.created_at"
:user="post.user" />
</div>
<button @click="getPosts()"> More </button>
</div>

Loading…
Cancel
Save