Hey I am creating a blog website and I would like to make it so that I can see all the posts and the user can only see their own. How do I do that?
My CreatePostController:
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use App\Models\Comment;
use Illuminate\Validation\Rule;
class CreatePostController extends Controller
{
public function index()
{
return view('create.index', [
'posts' => Post::paginate(50)
]);
}
public function create()
{
return view('create.create');
}
public function store()
{
Post::create(array_merge($this->validatePost(), [
'user_id' => request()->user()->id,
'thumbnail' => request()->file('thumbnail')->store('thumbnails')
]));
return redirect('/');
}
public function edit(Post $post)
{
return view('create.edit',
['post' => $post]);
}
public function update(Post $post)
{
$attributes = $this->validatePost($post);
if ($attributes['thumbnail'] ?? false) {
$attributes['thumbnail'] = request()->file('thumbnail')->store('thumbnails');
}
$post->update($attributes);
return back()->with('success', 'Post updated!');
}
public function destroy(Post $post)
{
$post->delete();
return back()->with('success', 'Post deleted!');
}
protected function validatePost(?Post $post = null): array
{
$post ??= new Post();
return request()->validate([
'title' => 'required|min:3|max:32',
'thumbnail' => $post->exists ? ['image'] : ['required', 'image'],
'slug' => ['required', Rule::unique('posts', 'slug')->ignore($post)],
'excerpt' => 'required',
'body' => 'required',
'link' => 'nullable|url',
'category_id' => ['required', Rule::exists('categories', 'id')]
]);
}
}
and my Post index:
<x-layout>
<x-setting heading="My Blogposts">
<div class="flex flex-col">
<div class="-my-2 overflow-x-auto sm:-mx-6">
<div class="py-2 align-middle inline-block min-w-full sm:px-6 lg:px-8">
<div class="shadow overflow-hidden border-b border-gray-200">
<table class="min-w-full divide-y divide-gray-200">
<tbody class="bg-white divide-y divide-gray-200">
@foreach ($posts as $post)
<tr>
<td class="px-6 py-4 whitespace-nowrap">
<div class="flex items-center">
<div class="text-sm font-medium text-gray-900">
<a href="/posts/{{ $post->slug }}">
{{ $post->title }}
</a>
</div>
</div>
</td>
<td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
<a href="/create/posts/{{ $post->id }}/edit" class="text-red-500 hover:text-red-600">Edit</a>
</td>
<td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
<form method="POST" action="/create/posts/{{ $post->id }}">
@csrf
@method('DELETE')
<button class="text-xs text-gray-400">Delete</button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</x-setting>
</x-layout>