그냥 사는 이야기

Laravel 5.3 Blog System - Admin Dashboard - Create, Store 본문

Development/Web

Laravel 5.3 Blog System - Admin Dashboard - Create, Store

없다캐라 2020. 1. 23. 15:38
반응형

Create, Store Post 생성

App/Http/Controllers/Auth/PostController
public function create(Request $request)
{
    // if user can post i.e. user is admin or author
    if ($request->user()->can_post()) {
      return view('admin/posts/create');
    } else {
      return redirect('/')->withErrors('You have not sufficient permissions for writing post');
    }
}

public function store(Request $request)
{
    $post = new Post();
    $post->title = $request->get('title');
    $post->description = $request->get('description');
    $post->body = $request->get('body');
    $post->slug = str_slug($post->title);
    $post->author_id = $request->user()->id;

    // thumbnail upload
    if ($request->file('images')) {
        $fileName = str_random(30);
        $request->file('images')->move("img/",$fileName);
    } else {
        $fileName = $post->images;
    }
    $post->images = $fileName;

    if ($request->has('save')) {
        // for draft
        $post->active = 0;
        $message = 'Post saved successfully';
    } else {
        // for posts
        $post->active = 1;
        $message = 'Post published successfully';
    }
    $post->save();
    return redirect('admin/posts/editpost/'.$post->slug)->withMessage($message);
}

TinyMCE package

TinyMCE Download packge 참조

resources/views/admin/posts/create.blade.php
@extends('layouts.dashboard')

@section('content')
    <h2>Create New Post</h2>
    <script type="text/javascript" src="//cdn.tinymce.com/4/tinymce.min.js"></script>
    <script type="text/javascript">
    tinymce.init({
        selector : "textarea",
        plugins : ["advlist autolink lists link image charmap print preview anchor", "searchreplace visualblocks code fullscreen", "insertdatetime media table contextmenu paste"],
        toolbar : "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image"
    });
    </script>

    <form action="{{ url('/admin/posts/createpost') }}" method="post" enctype="multipart/form-data">
        <input type="hidden" name="_token" value="{{ csrf_token() }}">
        <div class="form-group">
            <p>Title</p>
            <input type="text" name="title" value="{{ old('title') }}" required="required" placeholder="Enter title here" class="form-control">
            <br>
            <p>Description</p>
            <input type="text" name="description" value="{{ old('description') }}" required="required" placeholder="Enter description here" class="form-control">
            <br>

            <!-- thumbnail upload -->
            <p>Thumbnail</p>
            <img src="http://placehold.it/100x100" id ="showimages" style="max-width:200px;max-height:200px;float:left;"/>
            <div class="row">
                <div class="col-md-12">
                    <input type="file" id="inputimages" name="images">
                </div>
            </div>
        </div>

        <div class="form-group">
            <textarea name='body'class="form-control" rows="20"></textarea>
        </div>
        <input type="submit" name='publish' class="btn btn-success" value = "Publish"/>
        <input type="submit" name='save' class="btn btn-default" value = "Save Draft" />
    </form>
@endsection
routes/web.php
Route::group(['middleware' => ['auth']], function() {
    ...
    // show new post form
    Route::get('admin/posts/new-post','Auth\PostsController@create');
    // save new post
    Route::post('admin/posts/createpost','Auth\PostsController@store');

    Route::resource('admin/posts', 'Auth\PostController');
});

순서에 주의

Add some function in user model(for authentication)

app/user.php
public function can_post()
{
    $role = $this->role;
    if($role == 'author' || $role == 'admin') {
        return true;
    }
    return false;
}

public function is_admin()
{
    $role = $this->role;
    if($role == 'admin') {
        return true;
    }
    return false;
}

public function posts()
{
    return $this->hasMany('App\Posts','author_id');
}

public function comments()
{
    return $this->hasMany('App\Comments','from_user');
}
resources/views/admin/posts/create.blade.php
...
        <!-- show images thumbnail in create/edit page -->
        <script type="text/javascript">
            function readURL(input) {
                if (input.files && input.files[0]) {
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        $('#showimages').attr('src', e.target.result);
                    }
                    reader.readAsDataURL(input.files[0]);
                }
            }
            $("#inputimages").change(function () {
                readURL(this);
            });
        </script>
    </body>
</html>

마지막에 섬네일 preview를 위한 java script를 추가한다.

Comments