1. 라라벨 프로젝트 설치

composer create-project laravel/laravel inertia --prefer-dist 6.0


2. 데이터베이스 설정 ( .env)


3. 마이그레이션 실행

php artisan migrate


4. 이터니아 라라벨 어댑터 설치

https://inertiajs.com/server-side-setup

1
composer require inertiajs/inertia-laravel
cs


5. 루트 템플릿 설정 resources/views/app.blade.php

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
    <link href="{{ mix('/css/app.css') }}" rel="stylesheet" />
    <script src="{{ mix('/js/app.js') }}" defer></script>
  </head>
  <body>
    @inertia
  </body>
</html>
cs


6. npm과 vue 어댑터 설치

https://inertiajs.com/client-side-setup

1
npm install @inertiajs/inertia @inertiajs/inertia-vue
cs


7. webpack.mix.js

const mix = require('laravel-mix');

mix.js('resources/js/app.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css')
.webpackConfig({
output: { chunkFilename: 'js/[name].js?id=[chunkhash]' },
resolve: {
alias: {
vue$: 'vue/dist/vue.runtime.esm.js',
'@': path.resolve('resources/js'),
},
},
});


8. 동적가져오기 활성화

1
npm install @babel/plugin-syntax-dynamic-import
cs


프로젝트명/.babelrc 파일생성 후 다음 소스 작성

1
2
3
{
  "plugins": ["@babel/plugin-syntax-dynamic-import"]
}
cs


9. resources/js/app.js 아래처럼 교체

https://inertiajs.com/client-side-setup

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { InertiaApp } from '@inertiajs/inertia-vue'
import Vue from 'vue'
 
Vue.use(InertiaApp)
 
const app = document.getElementById('app')
 
new Vue({
  render: h => h(InertiaApp, {
    props: {
      initialPage: JSON.parse(app.dataset.page),
      resolveComponent: name => import(`./Pages/${name}`).then(module => module.default),
    },
  }),
}).$mount(app)
 
cs


10. npm 패키지 설치

npm install


11. 빌드

npm run watch


12. 에러시 

npm install --save vue


13. resources/js/Pages/Welcome.vue  생성


14. web.php 설정

1
2
3
4
5
6
7
8
9
<?php
 
use Inertia\Inertia;
 
Route::get('/', function () {
    return Inertia::render('Welcome',[
       'foo' => 'bar'
    ]);
});
cs


15. resources/js/Pages/Welcome.vue 변수 값 들어오는지 확인

1
2
3
4
5
6
7
8
9
10
11
<template>
  <div>
      Welcome Page{{ foo }}
  </div>
</template>
 
<script>
export default {
     props: ['foo']
}
</script>
cs


16. 브라우저확인


17. main틀을 만들자

resources/js/Shared/Layout.vue

<template>
<main>
<header>
<inertia-link href="/">Home</inertia-link>
<inertia-link href="/about">About</inertia-link>
<inertia-link href="/contact">Contact</inertia-link>

</header>

<article>
<slot/>
</article>

</main>
</template>

<script>
export default {

}
</script>

<style>

</style>


18. welcome.vue    

<layout> 감싸자

<template>
<layout>

<div>
Welcome Page{{ foo }}
</div>
</layout>
</template>

<script>
import Layout from '@/Shared/Layout'

export default {
props: ['foo'],

components:{
Layout
},
}
</script>




19. 부트스트랩 디자인 적용

1
composer require laravel/ui "^1.2"
cs


1
php artisan ui bootstrap --auth
cs


npm install


npm run watch


20. Layout.vue

<template>
<main>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<inertia-link href="/" class="nav-item nav-link">Home</inertia-link>
<inertia-link href="/about" class="nav-item nav-link">About</inertia-link>
<inertia-link href="/contact" class="nav-item nav-link">Contact</inertia-link>
</div>
</div>
</nav>

<article>
<slot />
</article>
</main>
</template>




21. 팅커콘솔에서 다음과 같이 입력

factory('App\User',30)->create()

그럼 users테이블에 30row 가짜 데이터가 입력되었을 것이다.


22. UsersControllers -r 을 만들어준다.

php artisan make:controller UsersController -r

public function index()
{
$users = User::all();

return Inertia::render('Users/Index',[
'users' => $users,
]);
}


23. web.php 파일에서 라우터를 정의해준다.

Route::get('/users', 'UsersController@index')->name('users.index');


24. resources/js/Pages/Users/Index.vue 생성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<template>
    <layout>
 
        <div>
            users Page
        </div>
 
    </layout>
</template>
 
<script>
import Layout from '@/Shared/Layout'
 
export default {
     props: ['users'],
 
     components:{
         Layout
     },
}
</script>
 
cs


25.  브라우저 확인


26. Index.vue 디자인 수정

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
32
33
34
35
36
37
38
39
40
41
42
<template>
  <layout>
    <div class="container">
      <div v-if="successMessage" class="alert alert-success mt-4">
        {{ successMessage }}
      </div>
 
      <div class="my-5">
        <a href="/users/create" class="btn btn-primary">Create User</a>
      </div>
      <table class="table table-striped">
        <thead>
          <tr>
            <th scope="col">Name</th>
            <th scope="col">Email</th>
            <th scope="col">Actions</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="user in users" :key="user.id">
            <td>{{ user.name }}</td>
            <td>{{ user.email }}</td>
            <td>
              <inertia-link :href="`/users/${user.id}/edit`">Edit</inertia-link>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </layout>
</template>
 
<script>
import Layout from '@/Shared/Layout'
export default {
 props: ['users''successMessage'],
  components: {
    Layout,
  },
}
</script>
 
cs



27. web.php 파일에 CRUD에 대한 라우터를 모두 정의한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 유저목록
Route::get('/users', 'UsersController@index')->name('users.index');
 
// 유저생성 페이지
Route::get('/users/create', 'UsersController@create')->name('users.create');
 
//유저 생성 로직 처리
Route::post('/users', 'UsersController@store')->name('users.store');
 
//유저 수정 페이지
Route::get('/users/{user}/edit', 'UsersController@edit')->name('users.edit');
 
// 유저 수정 로직 처리
Route::patch('/users/{user}', 'UsersController@update')->name('users.update');
 
// 유저 삭제
Route::delete('/users/{user}', 'UsersController@destroy')->name('users.destroy');
cs


28. UsersController.php

public function create()
{
return Inertia::render('Users/Create');
}


29. resources/js/Pages/Users/Create.vue 생성

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<template>
  <layout>
    <div class="container">
      <div class="col-md-6">
 
        <form action="/users" method="POST" class="my-5" @submit.prevent="createUser">
          <div class="form-group">
            <label for="name">Name</label>
            <input type="text" class="form-control" id="name" placeholder="Name" v-model="form.name">
          </div>
          <div class="form-group">
            <label for="email">Email</label>
            <input type="email" class="form-control" id="email" placeholder="Email" v-model="form.email">
          </div>
          <div class="form-group">
            <label for="password">Password</label>
            <input type="password" class="form-control" id="password" placeholder="Password" v-model="form.password">
          </div>
          <button type="submit" class="btn btn-primary">Create User</button>
        </form>
      </div>
    </div>
  </layout>
</template>
 
<script>
import Layout from '@/Shared/Layout'
export default {
 props: ['errors'],
  components: {
    Layout,
  },
  data() {
    return {
      form: {
        name'',
        email: '',
        password: '',
      }
    }
  },
  methods: {
    createUser() {
      this.$inertia.post('/users', this.form)
        .then(() => {
          // code
        })
    }
  }
}
</script>
 
cs



30. UsersController.php

public function store(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:5'
]);

User::create([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password)
]);

return redirect()->route('users.index')->with('successMessage','등록이 완료 되었습니다.');
}


31. 글을 작성해본다.


32. Layout.vue 하단에 아래와 같이 작성한다.

<script>
export default{
inject: ['page'],
}
</script>


33. Create.vue

props: ['errors'],


34. app/Providers/AppServiceProvider.php  다음과 같이 작성하자(오류 통신공유)

public function register()
{
Inertia::share('app.name', config('app.name'));

Inertia::share('errors', function () {
return session()->get('errors') ? session()->get('errors')->getBag('default')->getMessages() : (object) [];
});

Inertia::share('successMessage', function () {
return session()->get('successMessage') ? session()->get('successMessage') : null;
});
}


35. Create.vue 오류메시지 삽입

<div v-if="Object.keys(errors).length > 0" class="alert alert-danger mt-4">
{{ errors[Object.keys(errors)[0]][0] }}
</div>



36. 성공메시지를 넣어보자

app/Providers/AppServiceProvider.php  다음과 같이 작성하자(오류 통신공유)

//성공 메시지
Inertia::share('successMessage', function () {
return session()->get('successMessage') ? session()->get('successMessage') : null;
});


37. Index.vue

<div v-if="successMessage" class="alert alert-success mt-4">
{{ successMessage }}
</div>


props: ['users', 'successMessage'],



38. UsersController.php

public function edit(User $user)
{
return Inertia::render('Users/Edit',[
'user' => $user,
]);
}


39. resources/js/Pages/Users/Edit.vue 작성

<template>
<layout>
<div class="container">
<div class="col-md-6">
<div v-if="Object.keys(errors).length > 0" class="alert alert-danger mt-4">
{{ errors[Object.keys(errors)[0]][0] }}
</div>
<form action="#" method="PATCH" class="my-5" @submit.prevent="updateUser">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" placeholder="Name" v-model="form.name">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" placeholder="Email" v-model="form.email">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" placeholder="Password" v-model="form.password">
</div>
<button type="submit" class="d-flex btn btn-primary" :disabled="loading">
<span>Update User</span>
</button>
</form>

<button class="btn btn-danger" @click="deleteUser">Delete User</button>
</div>
</div>
</layout>
</template>

<script>
import Layout from '@/Shared/Layout'
export default {
components: {
Layout,
},
props: ['user', 'errors'],
data() {
return {
loading: false,
form: {
name: this.user.name,
email: this.user.email,
}
}
},
methods: {
updateUser() {
this.loading = true;
this.$inertia.patch(`/users/${this.user.id}`, this.form)
.then(() => {
this.loading = false;
})
},
deleteUser() {
if (confirm('Are you sure you want to delete this contact?')) {
this.$inertia.delete(`/users/${this.user.id}`)
.then(() => {
})
}
}
}
}
</script>



40. UsersController.php

public function update(Request $request, User $user)
{
$request->validate([
'name' => 'required',
'email' => 'required|unique:users,email,'.$user->id, //다른 사람 이메일인지 확인
]);

$user->update([
'name' => $request->name,
'email' => $request->email
]);

return redirect()->route('users.index')->with('successMessage','업데이트 완료!');
}


'라라벨 > Inertia.js' 카테고리의 다른 글

Inertia.js란  (0) 2020.04.15
Laravel + Inertia.js 예제  (0) 2020.04.15

+ Recent posts