基於Laravel開發博客應用系列 —— 十分鐘搭建博客系統

一、建立文章數據表及其模型(0:00~2:30)

咱們已經在上一節中爲博客項目完成了大部分準備工做,如今首先要作的就是爲這個項目建立一個新的文章表 posts及該表對應的模型類 Post,使用以下Artisan命令便可完成這兩個建立工做:php

php artisan make:model --migration Post

上述命令會作兩件事情:css

  •  app 目錄下建立模型類 App\Post
  • 建立用於建立 posts 表的遷移,該遷移文件位於 database/migrations 目錄下。

注:若是不瞭解什麼是遷移,可參考 Laravel 遷移文檔html

編輯 database/migrations 目錄下剛生成的這個遷移文件內容以下:laravel

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{

    /**
     * Run the migrations.
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('slug')->unique();
            $table->string('title');
            $table->text('content');
            $table->timestamps();
            $table->timestamp('published_at')->index();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down()
    {
        Schema::drop('posts');
    }
}

咱們在默認生成的遷移文件基礎上新增四個額外的列:web

  • slug:將文章標題轉化爲URL的一部分,以利於SEO
  • title:文章標題
  • content:文章內容
  • published_at:文章正式發佈時間

登陸到 Homestead 虛擬機項目根目錄(~/Code/vagrant/blog)運行遷移命令:數據庫

php artisan migrate

最後修改生成的默認 app/Post.php 文件內容以下:bootstrap

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $dates = ['published_at'];

    public function setTitleAttribute($value)
    {
        $this->attributes['title'] = $value;

        if (! $this->exists) {
            $this->attributes['slug'] = str_slug($value);
        }
    }
}

二、使用測試數據填充文章表(2:30~5:00)

有了第一步操做,如今文章已經有了寄身之所,接下來咱們不妨建立一些隨機數據填充到數據表 posts 中。這裏咱們要用到 Laravel 5.1 的模型工廠功能。瀏覽器

添加以下代碼到 database/factories 目錄下的 ModelFactory.php 文件中:app

$factory->define(App\Post::class, function ($faker) {
    return [
        'title' => $faker->sentence(mt_rand(3, 10)),
        'content' => join("\n\n", $faker->paragraphs(mt_rand(3, 6))),
        'published_at' => $faker->dateTimeBetween('-1 month', '+3 days'),
    ];
});

而後修改 database/seeds 目錄下的 DatabaseSeeder.php 內容以下:函數

<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run()
    {
        Model::unguard();
        $this->call('PostTableSeeder');
    }

}

class PostTableSeeder extends Seeder
{
    public function run()
    {
        App\Post::truncate();
        factory(App\Post::class, 20)->create();
    }
}

最後,仍是在 Homestead 虛擬機項目根目錄下運行以下 Artisan 命令將隨機數據插入數據庫:

php artisan db:seed

該命令執行成功後,posts 表中會多出20行記錄。

三、建立配置文件(5:00~5:30)

咱們還須要爲博客作一些配置,好比標題和每頁顯示文章數。時間很少了,讓咱們快速行動起來。

 config 目錄下建立一個新的配置文件 blog.php,編輯其內容以下:

<?php
return [
        'title' => 'My Blog',
        'posts_per_page' => 5
];

在 Laravel 5.1 中,能夠輕鬆經過幫助函數 config() 訪問這些配置項,例如,config('blog.title') 將會返回title 配置項的值。

此外,若是須要的話你還能夠去 config/app.php 修改時區配置。

四、建立路由控制器(5:30~7:30)

接下來修改 app/Http/routes.php 文件以下:

<?php

get('/', function () {
    return redirect('/blog');
});

get('blog', 'BlogController@index');
get('blog/{slug}', 'BlogController@showPost');

這樣,若是訪問 http://blog.app/ 的話,頁面會重定向到 http://blog.app/blog,而訪問 http://blog.app/blog時,會調用  BlogController 的 index 方法來處理業務邏輯並渲染頁面。同理訪問 http://blog.app/blog/POST-TITLE 時,會調用  BlogController 的 showPost 方法,同時會將 POST-TITLE 的值做爲參數傳遞給 showPost 方法。

下面咱們就來建立這個控制器 BlogController

首先,使用 Artisan 命令生成一個空的控制器:

php artisan make:controller BlogController --plain

注:--plain 命令用於建立一個空的控制器而不是標準的 RESTful 風格控制器。

一個新的 BlogController.php 文件已經生成到 app/Http/Controllers 目錄下,編輯其內容以下:

<?php

namespace App\Http\Controllers;

use App\Post;
use Carbon\Carbon;

class BlogController extends Controller
{
    public function index()
    {
        $posts = Post::where('published_at', '<=', Carbon::now())
                ->orderBy('published_at', 'desc')
                ->paginate(config('blog.posts_per_page'));

        return view('blog.index', compact('posts'));
    }

    public function showPost($slug)
    {
        $post = Post::whereSlug($slug)->firstOrFail();
        return view('blog.post')->withPost($post);
    }
}

在控制器中,咱們使用 Eloquent ORM 與數據庫進行交互,並使用輔助函數 view() 渲染視圖

若是要查看應用中的全部路由,可使用以下命令:

php artisan route:list

五、建立視圖(7:30~10:00)

剩下的就是建立兩個視圖用來顯示結果了:一個用於顯示文章列表,一個用於顯示文章詳情。

 resources/views 目錄下建立一個新的目錄 blog。而後在該目錄下建立一個新的視圖文件 index.blade.php。使用 .blade.php 後綴的目的在於告知 Laravel 該視圖文件使用 Blade 模板。編輯 index.blade.php 文件內容以下:

<html>
    <head>
        <title>{{ config('blog.title') }}</title>
        <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body>
        <div class="container">
            <h1>{{ config('blog.title') }}</h1>
            <h5>Page {{ $posts->currentPage() }} of {{ $posts->lastPage() }}</h5>
            <hr>
            <ul>
            @foreach ($posts as $post)
                <li>
                    <a href="/blog/{{ $post->slug }}">{{ $post->title }}</a>
                    <em>({{ $post->published_at }})</em>
                    <p>
                        {{ str_limit($post->content) }}
                    </p>
                </li>
            @endforeach
            </ul>
            <hr>
            {!! $posts->render() !!}
        </div>
    </body>
</html>

十分鐘博客的最後一步就是就是建立顯示文章詳情的視圖。在 resources/views/blog 目錄下新建視圖文件post.blade.php,編輯其內容以下:

<html>
    <head>
        <title>{{ $post->title }}</title>
        <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body>
        <div class="container">
            <h1>{{ $post->title }}</h1>
            <h5>{{ $post->published_at }}</h5>
            <hr>
                {!! nl2br(e($post->content)) !!}
            <hr>
            <button class="btn btn-primary" onclick="history.go(-1)">
                « Back
            </button>
        </div>
    </body>
</html>

好了,接下來咱們能夠去瀏覽器中進行測試了,訪問 http://blog.app,頁面顯示以下:

Laravel建立的博客首頁

文章詳情頁顯示以下:

Laravel建立的博客文章頁

相關文章
相關標籤/搜索