반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |
Tags
- 인민공원
- 이더리움
- 개인사업자
- win32
- 보정명령
- blockchain
- 홈택스
- Tutorial
- Laravel
- auth
- reactnative
- 코로나19
- as후기
- elasticSearch
- javascript
- 사업자계좌
- Sentinel
- Eclipse
- 전자소송
- Java
- Python
- cartalyst
- Bootstrap
- 코로나
- 체당금
- php
- 당사자표시정정신청서
- Blade
- vue
- 소액임금체불
Archives
- Today
- Total
그냥 사는 이야기
Laravel 5.3 Blog System - Post And Comments 본문
반응형
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');
});
'Development > Web' 카테고리의 다른 글
Laravel 5.3 Blog System - Admin Dashboard (0) | 2020.01.23 |
---|---|
Laravel 5.3 Blog System - Bootstrap theme view (0) | 2020.01.22 |
Laravel 5.3 Blog System - Setup Database (0) | 2020.01.22 |
Laravel 5.3 Sentinel - Visitors & Manager (0) | 2020.01.21 |
Laravel 5.3 Sentinel - Restricting Access According to Roles (0) | 2020.01.21 |
Comments