[Laravel8/Vue2 SPA] Laravel-vue-crud-starter를 이용한 게시판 CRUD(2)-Create

최가희·2022년 1월 14일
0

Laravel 8

목록 보기
3/6
post-thumbnail

create 기능 구현


01. newModal() 메소드 구현

글을 작성할 수 있는 모달 활성화

resources > js > components > board > Board.vue

<script>
    export default{
	...
	 methods: {
          newModal(){
                  this.editmode = false;
                  this.form.reset();
                  $('#addNew').modal('show');
          }
     }
}
</script>


02. createPost() 메소드 구현

resources > js > components > board > Board.vue

<script>
   export default{
	...
	 methods: {
         ...
         createPost(){
               this.$Progress.start(); //vue-progressbar
               this.form.post('api/board')
               .then((res)=>{
                   if(res.data.success){
                       $('#addNew').modal('hide');
                       Toast.fire({
                           icon: 'success',
                           title: res.data.message
                       });
                       this.$Progress.finish();
                   //this.loadPosts();
                   } else {
                       Toast.fire({
                           icon: 'error',
                           title: 'Some error occured! Please try again'
                       });
                       this.$Progress.failed();
                   }
               })
               .catch(()=>{
                   Toast.fire({
                       icon: 'error',
                       title: 'Some error occured! Please try again'
                   });
               })
           },
    }
}
</script>

03. PostRequest 작성

app > Http > Requests > Board 디렉토리 생성 > PostRequest.php 생성

<?php

namespace App\Http\Requests\Board;

use Illuminate\Foundation\Http\FormRequest;

class PostRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        if ($this->isMethod('post')) {
            return $this->createRules();
        } elseif ($this->isMethod('put')) {
            return $this->updateRules();
        }
    }
    /**
     * Define validation rules to store method for resource creation
     *
     * @return array
     */
    public function createRules(): array
    {
        return [
            'title' => 'required|string|max:191',
            'content' => 'required|string|max:1000',
            'author' => 'required|string|max:191',
            'photo' => 'nullable|files',
        ];
    }

    /**
     * Define validation rules to update method for resource update
     *
     * @return array
     */  
}

04. BoardController 작성

app > Http > Controllers > API > V1 > BoardController.php

<?php

namespace App\Http\Controllers\API\V1;

use App\Http\Requests\Board\PostRequest;
use App\Models\Board;
use Illuminate\Http\Request;

class BoardController extends BaseController
{
    protected $board = '';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct(Board $board)
    {
        $this->middleware('auth:api');
        $this->board = $board;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(PostRequest $request)
    {
        $board = $this->board->create([
            'title' => $request->get('title'),
            'content' => $request->get('content'),
            'author' => $request->get('author'),
            'photo' => $request->get('photo'),
        ]);

        return $this->sendResponse($board, 'Post Created Successfully');
    }
}

05. api.php에 코드 추가

routes > api.php

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;

...

Route::namespace('App\\Http\\Controllers\\API\V1')->group(function () {
    Route::get('profile', 'ProfileController@profile');
    Route::put('profile', 'ProfileController@updateProfile');
    Route::post('change-password', 'ProfileController@changePassword');
    Route::get('tag/list', 'TagController@list');
    Route::get('category/list', 'CategoryController@list');
    Route::post('product/upload', 'ProductController@upload');
    //Route::post('board', 'BoardController@store'); // 추가 -> 2022.01.20 수정 ~ 추가 안 해도 apiResources에 의해 자동으로 매핑됨

    Route::apiResources([
        'user' => 'UserController',
        'product' => 'ProductController',
        'category' => 'CategoryController',
        'tag' => 'TagController',
        'board' => 'BoardController', // 추가
    ]);
});

npm run dev 실행 뒤 글을 등록해보자.

글이 성공적으로 등록되었다는 vue-progressbar가 뜬다.

DB에도 잘 저장되었다. id가 3인 이유는 전에 2개 등록했다가 지워서다^_^

0개의 댓글