80 lines
1.9 KiB
PHP
80 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Models\Post;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Gate;
|
|
|
|
class PostController extends Controller
|
|
{
|
|
public function __construct()
|
|
{
|
|
$this->middleware('auth');
|
|
}
|
|
|
|
public function index()
|
|
{
|
|
$posts = Gate::allows('admin')
|
|
? Post::with('user')->latest()->paginate(10)
|
|
: Post::where('user_id', auth()->id())->with('user')->latest()->paginate(10);
|
|
|
|
return view('home', compact('posts'));
|
|
}
|
|
|
|
public function create()
|
|
{
|
|
return view('posts.create');
|
|
}
|
|
|
|
public function store(Request $request)
|
|
{
|
|
$validated = $request->validate([
|
|
'title' => 'required|string|max:255',
|
|
'content' => 'required|string',
|
|
]);
|
|
|
|
Post::create([
|
|
'title' => $validated['title'],
|
|
'content' => $validated['content'],
|
|
'user_id' => auth()->id(),
|
|
]);
|
|
|
|
return redirect()->route('home')->with('success', 'Post created successfully');
|
|
}
|
|
|
|
public function show(Post $post)
|
|
{
|
|
Gate::authorize('view-post', $post);
|
|
return view('posts.show', compact('post'));
|
|
}
|
|
|
|
public function edit(Post $post)
|
|
{
|
|
Gate::authorize('update-post', $post);
|
|
return view('posts.edit', compact('post'));
|
|
}
|
|
|
|
public function update(Request $request, Post $post)
|
|
{
|
|
Gate::authorize('update-post', $post);
|
|
|
|
$validated = $request->validate([
|
|
'title' => 'required|string|max:255',
|
|
'content' => 'required|string',
|
|
]);
|
|
|
|
$post->update($validated);
|
|
|
|
return redirect()->route('home')->with('success', 'Post updated successfully');
|
|
}
|
|
|
|
public function destroy(Post $post)
|
|
{
|
|
Gate::authorize('delete-post', $post);
|
|
|
|
$post->delete();
|
|
return redirect()->route('home')->with('success', 'Post deleted successfully');
|
|
}
|
|
}
|