laravel入門 3 (新增資料與顯示資料)
本張要介紹的方式是採用axios的方式來傳送資料到後端 , 至於為什麼要用axios呢 ? 因為Laravel的內建套件就是使用axios , 而他使用的方式跟ajax非常的像 , 所以不會很困難 , 特別要注意的是記得在blade.php的頁面 增加下列程式碼來引入
<!-- 載入Laravel的內建前端套件 ,現在目的是要載入Axios --> <script src="{{URL::asset('js/app.js')}}"></script>
新增資料庫(Insert)
views(home.blade.php)設定
<!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <!-- 引入google字體 --> <link href="https://fonts.googleapis.com/css?family=Lato:300,300i,400,400i,700,700i,900&subset=latin-ext" rel="stylesheet"> <style type="text/css"> body{ font-family: '微軟正黑體', 'Noto Sans TC', Helvetica, Arial, '黑體-繁', 'Heiti TC', '儷黑', 'LiHei', 'Microsoft JhengHei', sans-serif; } </style> <title>Note</title> </head> <body> <div class="container"> <div class="row"> <div class="col-12"> <h1 class="text-center mt-2">Note</h1> <input type="text" class="form-control mt-5" placeholder="標題" id="newTitle"> <textarea class="form-control mt-2" placeholder="內容" rows="3" id="newContent"></textarea> </div> <div class="col-12 text-right mt-2"> <button type="button" class="btn btn-primary" onclick="addItem()">新增</button> </div> <div class="col-12 mt-5"> <table class="table"> <thead class="thead-light"> <tr> <th width="200">標題</th> <th width="600">內容</th> <th>時間</th> <th style="min-width: 150px;">操作</th> </tr> </thead> <tbody> <tr> <td>Mark</td> <td>Otto</td> <th>2019-08-01 01:00:00</th> <td> <button type="button" class="btn btn-secondary" data-toggle="modal" data-target="#exampleModal">編輯</button> <button type="button" class="btn btn-danger">刪除</button> </td> </tr> <tr> <td>Jacob</td> <td>Thornton</td> <th>2019-08-01 01:00:00</th> <td> <button type="button" class="btn btn-secondary">編輯</button> <button type="button" class="btn btn-danger">刪除</button> </td> </tr> <tr> <td>Larry</td> <td>the Bird</td> <th>2019-08-01 01:00:00</th> <td> <button type="button" class="btn btn-secondary">編輯</button> <button type="button" class="btn btn-danger">刪除</button> </td> </tr> </tbody> </table> </div> </div> </div> <!-- 編輯視窗 --> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel"><b>編輯</b></h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <div class="form-group"> <label class="col-form-label">標題:</label> <input type="text" class="form-control"> </div> <div class="form-group"> <label class="col-form-label">內容:</label> <textarea class="form-control"></textarea> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">關閉</button> <button type="button" class="btn btn-primary">送出</button> </div> </div> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> <!-- 載入Laravel的內建前端套件 ,現在目的是要載入Axios --> <script src="{{URL::asset('js/app.js')}}"></script> </body> </html> <script type="text/javascript"> function addItem() { //取得資料 var title = $('#newTitle').val(); var content = $('#newContent').val(); //檢查有沒有填寫資料 if (!title) { alert('請填寫標題'); return } if (!content) { alert('請填寫內容'); return } //傳送到後端 axios.post('/addItem', { title:title, content:content }) .then(function (response) { if (response.data.result == 'success') { //後端回傳過來是成功後,重整頁面 location.reload(); } }) .catch(function (error) { console.log(error); }); } </script>
重點說明如下 :
新增id , 才能使用js去取得值
<input type="text" class="form-control mt-5" placeholder="標題" id="newTitle"> <textarea class="form-control mt-2" placeholder="內容" rows="3" id="newContent"></textarea>
再新增按鈕增加onclick事件 , 按下後會觸發 addItem函式
<button type="button" class="btn btn-primary" onclick="addItem()">新增</button>
傳送到後端的js程式碼
<script type="text/javascript"> function addItem() { //取得資料 var title = $('#newTitle').val(); var content = $('#newContent').val(); //檢查有沒有填寫資料 if (!title) { alert('請填寫標題'); return } if (!content) { alert('請填寫內容'); return } //傳送到後端 axios.post('/addItem', { title:title, content:content }) .then(function (response) { if (response.data.result == 'success') { //後端回傳過來是成功後,重整頁面 location.reload(); } }) .catch(function (error) { console.log(error); }); } </script>
route(routes/web.php)設定
//新增項目 Route::post('addItem','NoteController@addItem');
Controllers(app/Controllers/NoteController.php)設定
注意要增加 use App\Item;
新增addItem函式
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
//使用Item 這個model
use App\Item;
class NoteController extends Controller
{
public function home(Request $request)
{
return view('home');
}
//新增項目
public function addItem(Request $request)
{
//接收前端資料
$title = $request->input('title');
$content = $request->input('content');
//新增進資料庫
Item::insert([
//'資料庫欄位'=>資料
'title'=> $title,
'content'=> $content,
'created_at'=> NOW()
]);
//用json格式回傳結果
return response()->json(['result' => 'success']);
}
}
在畫面的標題跟內容各打上資料後,再按下新增 資料庫就有資料拉~
下一步我們就可以把資料庫的資料印出來到下方的表格嚕~
取出資料庫(Select)
在controller(控制器)導向畫面的時候 , 我們直接把資料庫的資料一起帶到畫面 , 然後再用php與html組合出完整的內容
Controllers(app/Controllers/NoteController.php)設定
public function home(Request $request) { //取得資料庫資料 $data = Item::select('id','title','content','created_at') //日期新到舊做排序 ->orderBy('created_at', 'desc') //最後一定要寫get()來結尾 , 不然會出錯 ->get(); //導向home.blade.php 並且帶上資料庫的資料 return view('home',['data'=>$data]); }
views(home.blade.php)設定
<!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <!-- 引入google字體 --> <link href="https://fonts.googleapis.com/css?family=Lato:300,300i,400,400i,700,700i,900&subset=latin-ext" rel="stylesheet"> <style type="text/css"> body{ font-family: '微軟正黑體', 'Noto Sans TC', Helvetica, Arial, '黑體-繁', 'Heiti TC', '儷黑', 'LiHei', 'Microsoft JhengHei', sans-serif; } </style> <title>Note</title> </head> <body> <div class="container"> <div class="row"> <div class="col-12"> <h1 class="text-center mt-2">Note</h1> <input type="text" class="form-control mt-5" placeholder="標題" id="newTitle"> <textarea class="form-control mt-2" placeholder="內容" rows="3" id="newContent"></textarea> </div> <div class="col-12 text-right mt-2"> <button type="button" class="btn btn-primary" onclick="addItem()">新增</button> </div> <div class="col-12 mt-5"> <table class="table"> <thead class="thead-light"> <tr> <th width="200">標題</th> <th width="600">內容</th> <th>時間</th> <th style="min-width: 150px;">操作</th> </tr> </thead> <tbody> <!-- 把假資料刪除後 , 將後端資料帶入html裡面 --> @foreach ($data as $val) <tr> <td>{{$val->title}}</td> <td>{{$val->content}}</td> <th>{{$val->created_at}}</th> <td> <button type="button" class="btn btn-secondary" data-toggle="modal" data-target="#exampleModal">編輯</button> <button type="button" class="btn btn-danger">刪除</button> </td> </tr> @endforeach </tbody> </table> </div> </div> </div> <!-- 編輯視窗 --> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel"><b>編輯</b></h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <div class="form-group"> <label class="col-form-label">標題:</label> <input type="text" class="form-control"> </div> <div class="form-group"> <label class="col-form-label">內容:</label> <textarea class="form-control"></textarea> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">關閉</button> <button type="button" class="btn btn-primary">送出</button> </div> </div> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> <!-- 載入Laravel的內建前端套件 ,現在目的是要載入Axios --> <script src="{{URL::asset('js/app.js')}}"></script> </body> </html> <script type="text/javascript"> function addItem() { //取得資料 var title = $('#newTitle').val(); var content = $('#newContent').val(); //檢查有沒有填寫資料 if (!title) { alert('請填寫標題'); return } if (!content) { alert('請填寫內容'); return } //傳送到後端 axios.post('/addItem', { title:title, content:content }) .then(function (response) { if (response.data.result == 'success') { //後端回傳過來是成功後,重整頁面 location.reload(); } }) .catch(function (error) { console.log(error); }); } </script>
重點說明 :
把假資料刪除後 , 將後端資料帶入html裡面
@foreach ($data as $val) <tr> <td>{{$val->title}}</td> <td>{{$val->content}}</td> <th>{{$val->created_at}}</th> <td> <button type="button" class="btn btn-secondary" data-toggle="modal" data-target="#exampleModal">編輯</button> <button type="button" class="btn btn-danger">刪除</button> </td> </tr> @endforeach
但會發現時間錯誤 , 問題再config/app.php 的 'timezone' => 'UTC' , 更正如下
'timezone' => 'Asia/Taipei',
設定完之後refresh可能還沒生效 , 要使用 CMD 執行
php artisan cache:clear
php artisan view:clear
php artisan config:cache
時間就正常了~
目前已經完成 顯示資料 與 新增資料 ,
下一章節我們將說明如何 修改資料 與 刪除資料 ~
我們下章節見嚕~
留言
張貼留言