首頁  >  文章  >  後端開發  >  使用laravel框架寫個小博客

使用laravel框架寫個小博客

巴扎黑
巴扎黑原創
2017-08-15 09:32:281948瀏覽

這篇文章主要給大家介紹了關於利用laravel搭建一個迷你博客的相關資料,文中將一步步的實現步驟通過示例代碼介紹的非常詳細,對大家具有一定的參考學習價值,需要的朋友們下面跟著小編來一起學習學習吧。

本文主要跟大家介紹的是關於利用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(&#39;blog.store&#39;)}}">
   {{ 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、設定資料庫

c.env檔

2、建立資料表

##利用artisan 指令產生遷移:

##

php artisan make:migration create_articles_talbe --create=articles

#修改遷移檔


public function up() 
 {
  Schema::create(&#39;articles&#39;, function (Blueprint $table) {
   $table->increments(&#39;id&#39;);
   $table->string(&#39;title&#39;);
   $table->longText(&#39;content&#39;);
   $table->timestamps();
  });
 }
public function down() 
 {
  Schema::dropIfExists(&#39;articles&#39;);
 }

我們建立了一張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 = &#39;articles&#39;;
 //通过model可以写入的字段
 protected $fillable = [
  &#39;title&#39;, &#39;content&#39;,
 ];
}
4、儲存邏輯程式碼




##開啟ArticlesController.php 控制器,找到store() 方法。

app/Http/Controllers/ArticlesController.php

#
 public function store(Request $request)
 {
  //数据验证 错误处理
  $this->validate($request,[
   &#39;title&#39;=>&#39;required|max:50&#39;,
   &#39;content&#39;=>&#39;required|max:500&#39;,
   ]);
  // 1 orm方式写入
  $article = Article::create([
   &#39;title&#39;=>$request->title,
   &#39;content&#39;=>$request->content,
   ]);
  //2 或者
  /* $article = new Article();
   $article->title =$request->title;
   $article->content = $request->content;
   $article->save();*/

   //3 db方式写入
   //insert()方法返回值为true 和 false
   //$res = DB::table(&#39;articles&#39;)->insert([&#39;title&#39;=>$request->title,&#39;content&#39;=>$request->content]);
  return redirect()->route(&#39;blog.index&#39;);
 }

驗證錯誤顯示

@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(&#39;created_at&#39;,&#39;asc&#39;)->get();

  return view(&#39;articles.index&#39;, [&#39;articles&#39;=>$articles]);
 }
###檢視index.blade.php############
@extends(&#39;layouts.art&#39;)
@section(&#39;content&#39;)

 <a class="btn btn-primary" href="{{route(&#39;blog.create&#39;)}}" rel="external nofollow" >添加文章</a>


 @foreach($articles as $article)
 <p class="panel panel-default">
 <p class="panel-body">
 {{$article->title}}
 <a href="{{route(&#39;blog.show&#39;,$article->id)}}" rel="external nofollow" class="btn btn-info">阅读</a>
 <a href="{{route(&#39;blog.edit&#39;, $article->id)}}" rel="external nofollow" class="btn btn-info">修改</a>

  <form action="{{ route(&#39;blog.destroy&#39;, $article->id) }}" method="post" style="display: inline-block;">
   {{ csrf_field() }}
   {{ method_field(&#39;DELETE&#39;) }}
   <button type="submit" class="btn btn-danger">删除</button>
  </form>
 </p>
 </p>
 @endforeach

 {!! $articles->render() !!}
 @endsection
#########八、編輯文章表單################################################### #####編輯文章表單其實和先前建立的新文章表單很類似,只是需要額外將現有的資料讀取出來填在表單上。 ######首先我們在文章清單頁的每個文章上新增一個編輯按鈕:######檢視:############
@extends(&#39;layouts.art&#39;)
@section(&#39;content&#39;)

 <form class="form-horizontal" method="post" action="{{route(&#39;blog.update&#39;,$article->id)}}">
   {{ csrf_field() }}
  {{ method_field(&#39;PATCH&#39;) }}
 <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(&#39;art.edit&#39;,[&#39;article&#39;=>$article]);
 }
//执行修改
public function update(Request $request, $id) 
 {
  $this->validate($request, [
   &#39;title&#39; => &#39;required|max:50&#39;,
   &#39;content&#39;=>&#39;required|max:500&#39;,
  ]);

  $article = Article::findOrFail($id);
  $article->update([
   &#39;title&#39; => $request->title,
   &#39;content&#39; => $request->content,
  ]);

   return redirect()->route(&#39;blog.index&#39;);
 }

九、删除文章

删除按钮


 <form action="{{ route(&#39;blog.destroy&#39;, $article->id) }}" method="post" style="display: inline-block;">
   {{ csrf_field() }}
   {{ method_field(&#39;DELETE&#39;) }}
   <button type="submit" class="btn btn-danger">删除</button>
  </form>

控制器:


public function destroy($id) 
 {
  $article = Article::findOrFail($id);
  $article->delete();
  return back();
 }

十、结语

本次实验通过一个很简单的迷你博客对 Laravel RESTful 资源控制器和路由,视图,orm进行了强化练习。

以上是使用laravel框架寫個小博客的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn