本文主要給大家介紹了關於利用laravel搭建一個迷你部落格的相關資料,文中將一步步的實現步驟通過範例程式碼介紹的非常詳細,對大傢具有一定的參考學習價值,希望能協助到大家。
一、設計與思路
在開始寫第一行代碼之前,一定要盡量從頭到尾將我們要做的產品設計好,避免寫完又改,多寫不必要的代碼。
需求分析:我們的迷你部落格應該至少包含:新增/編輯/查看/刪除文章,以及文章列表展示功能。
資料庫分析:基於這個功能,我們只需要一張 Articles 資料表來存放文章即可。
頁面結構分析:應該使用模板繼承建立一張基礎模板包含:頭部/文章列表/底部資訊
二、建立路由
完成這個部落格大概需要以下幾條路由:
| 路由 | 功能 | | -------- | ---------------- | | 文章列表頁面路由 | 返迴文章列表頁面 | | 新增文章頁面路由 | 返回新增文章頁面 | | 文章儲存功能路由 | 將文章儲存到資料庫 | | 查看文章頁面路由 | 返迴文章詳情頁面 | | 編輯文章頁面路由 | 返回編輯文章頁面 | | 編輯文章功能路由 | 將文章取出更新後重新儲存到資料庫 | | 刪除文章功能路由 | 將文章從資料庫刪除 |
可以看到幾乎全部是對文章的資料操作路由,針對這種情況,Laravel 提供了非常方便的辦法:RESTful 資源控制器和路由。
開啟routes.php加入如下代碼:
Route::resource('articles', 'ArticlesController');
只需要上面這樣一行代碼,就相當於建立了如下7條路由,且都是命名路由,我們可以使用類似route('articles.show') 這樣的用法。
Route::get('/articles', 'ArticlesController@index')->name('articles.index'); Route::get('/articles/{id}', 'ArticlesController@show')->name('articles.show'); Route::get('/articles/create', 'ArticlesController@create')->name('articles.create'); Route::post('/articles', 'ArticlesController@store')->name('articles.store'); Route::get('/articles/{id}/edit', 'ArticlesController@edit')->name('articles.edit'); Route::patch('/articles/{id}', 'ArticlesController@update')->name('articles.update'); Route::delete('/articles/{id}', 'ArticlesController@destroy')->name('articles.destroy');
三、建立控制器
利用 artisan 建立一個文章控制器:
php artisan make:controller ArticlesController
四、建立基礎視圖
resources/views/layouts/art.blade.php
見模板index.html
五、建立文章表單
@extends('layouts.art')@section('content') <form class="form-horizontal" method="post" action="{{route('blog.store')}}"> {{ csrf_field() }} <p class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">標題</label> <p class="col-sm-8"> <input type="title" class="form-control" id="title" name="title"> </p> </p> <p class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">內容</label> <p class="col-sm-8"> <textarea class="form-control" rows="5" id="content" name="content"></textarea> </p> </p> <p class="form-group"> <p class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">建立</button> </p> </p></form> @endsection
六、文章儲存
此時如果你填寫建立文章表單點擊提交也會跳到一個空白頁面,同樣的道理,因為我們後續的控制器代碼還沒寫。
要實現文章儲存,首先要設定資料庫,建立資料表,建立模型,然後再完成儲存邏輯代碼。
1、設定資料庫
修改.env檔案
2、建立資料表
利用 artisan 命令產生遷移:
php artisan make:migration create_articles_talbe --create=articles
修改遷移檔案
public function up() { Schema::create('articles', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->longText('content'); $table->timestamps(); }); }public function down() { Schema::dropIfExists('articles'); }
我們建立了一張 articles 表,包含遞增的 id 欄位,字串title欄位,長文本content欄位,和時間戳記。
執行資料庫遷移:
php artisan migrate
登入mysql,查看資料表。
3、建立模型
利用 artisan 命令建立模型:
php artisan make:model Article
開啟模型檔案,輸入以下代碼:
app/Article.php
namespace App;use Illuminate\Database\Eloquent\Model;class Article extends Model { //對應的表 protected $table = 'articles'; //通過model可以寫入的欄位 protected $fillable = [ 'title', 'content', ];}
4、儲存邏輯代碼
開啟 ArticlesController.php 控制器,找到 store() 方法。
app/Http/Controllers/ArticlesController.php
public function store(Request $request) { //資料驗證 錯誤處理 $this->validate($request,[ 'title'=>'required|max:50', 'content'=>'required|max:500', ]); // 1 orm方式寫入 $article = Article::create([ 'title'=>$request->title, 'content'=>$request->content, ]); //2 或者 /* $article = new Article(); $article->title =$request->title; $article->content = $request->content; $article->save();*/ //3 db方式寫入 //insert()方法傳回值為true 和 false //$res = DB::table('articles')->insert(['title'=>$request->title,'content'=>$request->content]); return redirect()->route('blog.index'); }
驗證錯誤顯示
@if (count($errors) > 0) <p class="alert alert-danger"> <ul> @foreach($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </p>@endif
七、文章列表展示
完成了添加文章功能後,就可以實現我們的文章列表展示頁了。
開啟 ArticlesController.php 找到 index() 方法,添加代碼如下:
app/Http/Controllers/ArticlesController.php
use App\Article;public function index() { $articles = Article::orderBy('created_at','asc')->get(); return view('articles.index', ['articles'=>$articles]); }
視圖index.blade.php
@extends('layouts.art')@section('content') <a class="btn btn-primary" href="{{route('blog.create')}}" rel="external nofollow" >添加文章</a> @foreach($articles as $article) <p class="panel panel-default"> <p class="panel-body"> {{$article->title}} <a href="{{route('blog.show',$article->id)}}" rel="external nofollow" class="btn btn-info">閱讀</a> <a href="{{route('blog.edit', $article->id)}}" rel="external nofollow" class="btn btn-info">修改</a> <form action="{{ route('blog.destroy', $article->id) }}" method="post" style="display: inline-block;"> {{ csrf_field() }} {{ method_field('DELETE') }} <button type="submit" class="btn btn-danger">刪除</button> </form> </p> </p> @endforeach {!! $articles->render() !!} @endsection
八、編輯文章表單
編輯文章表單其實和之前建立的建立文章表單很類似,只是需要額外將現有的資料讀取出來填在表單上。
首先我們在文章列表頁的每個文章上添加一個編輯按鈕:
視圖:
@extends('layouts.art')@section('content') <form class="form-horizontal" method="post" action="{{route('blog.update',$article->id)}}"> {{ csrf_field() }} {{ method_field('PATCH') }} <p class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">標題</label> <p class="col-sm-10"> <input type="title" class="form-control" id="title" name="title" value="{{ $article->title }}"> </p> </p> <p class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">內容</label> <p class="col-sm-10"> <textarea class="form-control" rows="5" id="content" name="content"> {{ $article->content }}</textarea> </p> </p> <p class="form-group"> <p class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">修改</button> </p> </p></form> @endsection
注意這段代碼中的 {{ method_field('PATCH') }} ,這是跨站方法偽造,HTML 表單沒有支援 PUT、PATCH 或 DELETE 動作。所以在從 HTML 表單中調用被定義的 PUT、PATCH 或 DELETE 路由時,你將需要在表單中增加隱藏的 _method 欄位來偽造該方法,詳情參考 官方文檔。
控制器
//展示修改模板public function edit($id) { $article = Article::findOrFail($id); return view('art.edit',['article'=>$article]); }//執行修改public function update(Request $request, $id) { $this->validate($request, [ 'title' => 'required|max:50', 'content'=>'required|max:500', ]); $article = Article::findOrFail($id); $article->update([ 'title' => $request->title, 'content' => $request->content, ]); return redirect()->route('blog.index'); }
九、刪除文章
刪除按鈕
<form action="{{ route('blog.destroy', $article->id) }}" method="post" style="display: inline-block;"> {{ csrf_field() }} {{ method_field('DELETE') }} <button type="submit" class="btn btn-danger">刪除</button> </form>
控制器:
public function destroy($id) { $article = Article::findOrFail($id); $article->delete(); return back(); }
十、結語
本次實驗通過一個很簡單的迷你部落格對 Laravel RESTful 資源控制器和路由,視圖,orm進行了強化練習。