创建标签模型和迁移
首先需要创建 Tag 模型类:php artisan make:model --migration Tag
该命令会在 app 目录下创建模型文件 Tag.php,由于我们在 make:model 命令中使用了 --migration 选项,所以同时会创建 Tag 模型对应的数据表迁移。在标签(Tag)和文章(Post)之间存在多对多的关联关系,因此还要按照下面的命令创建存放文章和标签对应关系的数据表迁移:php artisan make:migration --create=post_tag_pivot create_post_tag_pivot
在 database/migrations 目录下编辑新创建的标签迁移文件内容如下:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTagsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->increments('id');
$table->string('tag')->unique();
$table->string('title');
$table->string('subtitle');
$table->string('page_image');
$table->string('meta_description');
$table->string('layout')->default('blog.layouts.index');
$table->boolean('reverse_direction');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('tags');
}
}
对上面迁移文件中新增的字段作简要说明:
- page_image:标签图片
- meta_description:标签介绍
- layout:博客终归要使用布局
- reverse_directions:在文章列表按时间升序排列博客文章(默认是降序)
编辑文章与标签对应关系表迁移文件内容如下:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostTagPivot extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('post_tag_pivot', function (Blueprint $table) {
$table->increments('id');
$table->integer('post_id')->unsigned()->index();
$table->integer('tag_id')->unsigned()->index();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('post_tag_pivot');
}
}
运行迁移php artisan migrate
创建控制器添加路由
运行php artisan make:controller Admin\\TagController
创建控制器文件。
在routes/web.php文件中,将管理员路由改成以下内容:
Route::namespace('Admin')->middleware(['auth'])->group(function () {
Route::resource('admin/default', 'DefaultController');
Route::resource('admin/post', 'PostController');
Route::resource('admin/tag', 'TagController');
});
实现标签列表
在TagController 中添加index方法,具体引入的类可以参照之前的Post。
public function index()
{
$tags = Tag::orderBy('created_at', 'desc')
->paginate(config('blog.posts_per_page'));
return view('admin.tag.index')->withTags($tags);
}
在resources/views/admin/tag下创建index.blade.php视图文件
{% raw %}