그냥 사는 이야기

Laravel 5.3 Blog System - Post And Comments 본문

Development/Web

Laravel 5.3 Blog System - Post And Comments

없다캐라 2020. 1. 22. 10:52
반응형

Post와 Comment 구현

Model

App/Post
class Post extends Model
{
    protected $guarded = [];

    public function comments()
    {
        return $this->hasMany('App\Comment','on_post');
    }

    public function author()
    {
        return $this->belongsTo('App\User','author_id');
    }
}
App/Comment
class Comment extends Model
{
    protected $guarded = [];

    public function author()
    {
        return $this->belongsTo('App\User','from_user');
    }

    public function post()
    {
        return $this->belongsTo('App\Post','on_post');
    }
}

Controller

php artisan make:controller PostController --resource

php artisan make:controller CommentController --resource
App/Http/Controllers/PostController
use App\Post;
use App\User;
...
class PostController extends Controller
{
    public function index()
    {
        //fetch 5 posts from database which are active and latest
        $posts = Post::where('active',1)->orderBy('created_at')->paginate(2);
        // page Heading
        $title = 'Latest Post';

        return view('home')->withPosts($posts)->withTitle($title);
    }
    ...
    public function show($slug)
    {
        $post = Post::where('slug',$slug)->first();
        if (!$post) {
            return redirect('/')->withErrors('requested page not found');
        }

        $comments = $post->comments;

        return view('posts.show')->withPost($post)->withComments($comments);
    }
}
App/Http/Controllers/CommentController
use App\Post;
use App\Comment;
...
class CommentController extends Controller
{
    public function store(Request $request)
    {
        $input['from_user'] = $request->user()->id;
        $input['on_post'] = $request->input('on_post');
        $input['body'] = $request->input('body');
        $slug = $request->input('slug');

        Comment::create($input);

        return redirect($slug)->with('message', 'Comment published');
    }
    ...
}
Routes/web.php
Auth::routes();

Route::get('/',         'PostController@index');
Route::get('/home',     'PostController@index');
Route::get('/{slug}',   'PostController@show')->where('slug', '[A-Za-z0-9-_]+');
Route::group(['middleware' => ['auth']], function() {
    Route::post('comment/add','CommentController@store');
});
Comments