一、安裝Apache、MySQL、PHP環境
為了讓讀者能快速的撰寫程式,作者在Github上已經整理出一個適合開發Laravel的XAMPP環境。我們進到 https://github.com/superlevin/xamppforlaravel 點選 Clone or Download 後按 Download ZIP。
下載後,解壓縮到d:\xampp就可以運作了。執行 xampp-control 後,開啟相關服務即可。
二、安裝 composer,到 https://getcomposer.org/download/ 下載Composer-Setup.exe。
安裝時,將PHP路徑指向D:\xampp\php.exe
三、進入終端機模式(開始→執行 cmd),然後設定php到系統變數
set PATH=%PATH%;d:\xampp\php
四、phpmyadmin建立資料庫
進入 http://localhost:8899/phpmyadmin 網頁
建立新資料庫 laravelvuenotes
五、透過composer 建立 laravel專案
dos指定切換 d:\xampp\htdocs\ 輸入
composer create-project laravel/laravel laravelvuenote
六、建立完成後,進入laravel專案修改.env設定
八、刪除migration中其他沒用的檔案(二個都刪除)
八、dos模式下建立 migration,切換至 d:\xampp\htdocs\laravelvuenote,輸入
php artisan make:migration create_notes_table
修改laravelvuenote/database/migrations/XXXXX(日期)_xxxx(流水號)_create_notes_table.php
於up函數中加入
Schema::create('notes', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('content');
$table->timestamps();
});
於down函數中加入
Schema::drop('notes');
九、建立資料庫
dos模式下
php artisan migrate
十、新增model
dos模式下
php artisan make:model Note
十一、修改app\Note.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Note extends Model
{
//
protected $table ='notes';
public $fillable = ['title','content'];
}
十二、建立controller
php artisan make:controller NoteController --resource
十三、修改app\Http\Controllers\NoteController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Note;
use Validator;
use App\Http\Requests;
use Response;
use Illuminate\Support\Facades\Input;
class NoteController extends Controller
{
public function api()
{
return view('/api');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$notes = Note::latest()->paginate(6); //每頁為6
$response = [
'pagination' => [
'total' => $notes->total(),
'per_page' => $notes->perPage(),
'current_page' => $notes->currentPage(),
'last_page' => $notes->lastPage(),
'from' => $notes->firstItem(),
'to' => $notes->lastItem()
],
'data' => $notes
];
return response()->json($response);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request,[
'title' => 'required',
'content' => 'required',
]);
$create = Note::create($request->all());
return response()->json($create);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request,[
'title' => 'required',
'content' => 'required',
]);
$edit = Note::find($id)->update($request->all());
return response()->json($edit);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
Note::find($id)->delete();
return response()->json(['done']);
}
}
十四、修改routes\web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
//Route::get('/', function () {
// return view('welcome');
//});
Route::get('/', 'NoteController@api');
Route::get('/api', 'NoteController@index');
Route::resource('vuenotes','NoteController');
十五、建立頁面
在這邊我們使用jQuery、Bootstrap、toastr、Font awesome以及Vue.js 2
在resources/views建立app.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Laravel & Vue2 記事本</title>
<!-- Laravel CSRF-token check -->
<meta id="token" name="token" value="{{ csrf_token() }}">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container" id="manage-note">
@yield('content')
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<!-- vue.js -->
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.0.3/vue-resource.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" rel="stylesheet">
<!-- custom.js -->
<script type="text/javascript" src="./js/note.js?v=zxcvxzcv"></script>
</body>
</html>
接著新增檔案 api.blade.php
@extends('app')
@section('content')
<div class="form-group row">
<div class="col-md-12">
<h1><a href="https://laravel.com/" target="_blank">Laravel</a> & <a href="https://vuejs.org/" target="_blank">Vue.js 2</a> 記事本</h1>
<h2>其他使用: <a href="https://jquery.com/" target="_blank">jQuery</a>、<a href="http://getbootstrap.com/" target="_blank">Bootstrap</a>、<a href="http://codeseven.github.io/toastr/demo.html" target="_blank">toastr</a>、<a href="http://fontawesome.io/" target="_blank">Font awesome</a> </h2>
</div>
<div class="col-md-12">
<button type="button" data-toggle="modal" data-target="#create-note" class="btn btn-primary">
新增記事
</button>
</div>
</div>
<div class="row">
<div class="table-responsive">
<table class="table table-borderless">
<tr>
<th>標題</th>
<th>內容</th>
<th>動作</th>
</tr>
<tr v-for="note in notes">
<td>@{{ note.title }}</td>
<td>@{{ note.content }}</td>
<td>
<button class="edit-modal btn btn-warning" @click.prevent="editnote(note)">
<span class="glyphicon glyphicon-edit"></span> 修改
</button>
<button class="edit-modal btn btn-danger" @click.prevent="deletenote(note)">
<span class="glyphicon glyphicon-trash"></span> 刪除
</button>
</td>
</tr>
</table>
</div>
</div>
<nav>
<ul class="pagination">
<li v-if="pagination.current_page > 1">
<a href="#" aria-label="Previous" @click.prevent="changePage(pagination.current_page - 1)">
<span aria-hidden="true">«</span>
</a>
</li>
<li v-for="page in pagesNumber" v-bind:class="[ page == isActived ? 'active' : '']">
<a href="#" @click.prevent="changePage(page)">
@{{ page }}
</a>
</li>
<li v-if="pagination.current_page < pagination.last_page">
<a href="#" aria-label="Next" @click.prevent="changePage(pagination.current_page + 1)">
<span aria-hidden="true">»</span>
</a>
</li>
</ul>
</nav>
<!-- 新增對話框 -->
<div class="modal fade" id="create-note" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">新增記事</h4>
</div>
<div class="modal-body">
<form method="post" enctype="multipart/form-data" v-on:submit.prevent="createnote">
<div class="form-group">
<label for="title">標題:</label>
<input type="text" name="title" class="form-control" v-model="newnote.title" />
<span v-if="formErrors['title']" class="error text-danger">
@{{ formErrors['title'] }}
</span>
</div>
<div class="form-group">
<label for="title">內容:</label>
<textarea name="content" class="form-control" v-model="newnote.content">
</textarea>
<span v-if="formErrors['content']" class="error text-danger">
@{{ formErrors['content'] }}
</span>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">儲存</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- 修改對話框 -->
<div class="modal fade" id="edit-note" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">修改記事</h4>
</div>
<div class="modal-body">
<form method="post" enctype="multipart/form-data" v-on:submit.prevent="updatenote(fillnote.id)">
<div class="form-group">
<label for="title">標題:</label>
<input type="text" name="title" class="form-control" v-model="fillnote.title" />
<span v-if="formErrorsUpdate['title']" class="error text-danger">
@{{ formErrorsUpdate['title'] }}
</span>
</div>
<div class="form-group">
<label for="title">內容:</label>
<textarea name="content" class="form-control" v-model="fillnote.content">
</textarea>
<span v-if="formErrorsUpdate['content']" class="error text-danger">
@{{ formErrorsUpdate['content'] }}
</span>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">儲存</button>
</div>
</form>
</div>
</div>
</div>
</div>
@stop
最後在public/js/下新增note.js
Vue.http.headers.common['X-CSRF-TOKEN'] = $("#token").attr("value");
new Vue({
el :'#manage-note',
data :{
notes: [],
pagination: {
total: 0,
per_page: 2,
from: 1,
to: 0,
current_page: 1
},
offset: 4,
formErrors:{},
formErrorsUpdate:{},
newnote : {'title':'','content':''},
fillnote : {'title':'','content':'','id':''}
},
computed: {
isActived: function() {
return this.pagination.current_page;
},
pagesNumber: function() {
if (!this.pagination.to) {
return [];
}
var from = this.pagination.current_page - this.offset;
if (from < 1) {
from = 1;
}
var to = from + (this.offset * 2);
if (to >= this.pagination.last_page) {
to = this.pagination.last_page;
}
var pagesArray = [];
while (from <= to) {
pagesArray.push(from);
from++;
}
return pagesArray;
}
},
mounted: function () {
this.getVuenote(this.pagination.current_page);
},
methods: {
getVuenote: function(page) {
this.$http.get('/vuenotes?page='+page).then((response) => {
this.$set(this,'notes', response.data.data.data);
this.$set(this,'pagination', response.data.pagination);
});
},
createnote: function() {
var input = this.newnote;
this.$http.post('/vuenotes',input).then((response) => {
this.changePage(this.pagination.current_page);
this.newnote = {'title':'','content':''};
$("#create-note").modal('hide');
toastr.success('新增成功', '成功訊息', {timeOut: 5000});
}, (response) => {
this.formErrors = response.data;
});
},
deletenote: function(note) {
this.$http.delete('/vuenotes/'+note.id).then((response) => {
this.changePage(this.pagination.current_page);
toastr.success('刪除成功', '成功訊息', {timeOut: 5000});
});
},
editnote: function(note) {
this.fillnote.title = note.title;
this.fillnote.id = note.id;
this.fillnote.content = note.content;
$("#edit-note").modal('show');
},
updatenote: function(id) {
var input = this.fillnote;
this.$http.put('/vuenotes/'+id,input).then((response) => {
this.changePage(this.pagination.current_page);
this.newnote = {'title':'','content':'','id':''};
$("#edit-note").modal('hide');
toastr.success('更新成功', '成功訊息', {timeOut: 5000});
}, (response) => {
this.formErrors = response.data;
});
},
changePage: function(page) {
this.pagination.current_page = page;
this.getVuenote(page);
}
}
});
十六、開啟主機
php artisan serve
十七、完工