Laravel5.1 搭建博客 --構建標籤

博客的每篇文章都是須要有標籤的,它與文章也是多對多的關係 這篇筆記也是記錄了實現標籤的步驟邏輯。php

在咱們以前的筆記中建立了Tag的控制器和路由了 因此這篇筆記不在重複數組

 


1 建立模型與遷移文件

遷移文件以下:app

    public function up()
    {
        Schema::create('tags', function (Blueprint $table) {
            $table->increments('id');
            // tag的名字 惟一
            $table->string('tag')->unique();
            // tag的標題
            $table->string('title');
            // tag副標題
            $table->string('subtitle');
            // tag的圖片
            $table->string('page_image');
            // tag的描述
            $table->string('meta_description');
            // 要使用的佈局
            $table->string('layout')->default('blog.layouts.index');
            // 排序
            $table->boolean('reverse_direction');
            $table->timestamps();
        });
    }

 


2 展現Tag

在TagController的index方法添加以下代碼:佈局

    public function index()
    {
        $tags = Tag::all();
        return view('admin.tag.index')->withTags($tags);
    }

建立 index.blade.php 路徑是:views/admin/tagpost

@extends('admin.layout')

@section('content')
    <div class="container-fluid">
        <div class="row page-title-row">
            <div class="col-md-6">
                <h3>Tags <small>» Listing</small></h3>
            </div>
            <div class="col-md-6 text-right">
                <a href="/admin/tag/create" class="btn btn-success btn-md">
                    <i class="fa fa-plus-circle"></i> New Tag
                </a>
            </div>
        </div>

        <div class="row">
            <div class="col-sm-12">

                @include('admin.partials.error')
                @include('admin.partials.success')

                <table id="tags-table" class="table table-striped table-bordered">
                    <thead>
                    <tr>
                        <th>Tag</th>
                        <th>Title</th>
                        <th class="hidden-sm">Subtitle</th>
                        <th class="hidden-md">Page Image</th>
                        <th class="hidden-md">Meta Description</th>
                        <th class="hidden-md">Layout</th>
                        <th class="hidden-sm">Direction</th>
                        <th data-sortable="false">Actions</th>
                    </tr>
                    </thead>
                    <tbody>
                    @foreach ($tags as $tag)
                        <tr>
                            <td>{{ $tag->tag }}</td>
                            <td>{{ $tag->title }}</td>
                            <td class="hidden-sm">{{ $tag->subtitle }}</td>
                            <td class="hidden-md">{{ $tag->page_image }}</td>
                            <td class="hidden-md">{{ $tag->meta_description }}</td>
                            <td class="hidden-md">{{ $tag->layout }}</td>
                            <td class="hidden-sm">
                                @if ($tag->reverse_direction)
                                    Reverse
                                @else
                                    Normal
                                @endif
                            </td>
                            <td>
                                <a href="/admin/tag/{{ $tag->id }}/edit" class="btn btn-xs btn-info">
                                    <i class="fa fa-edit"></i> Edit
                                </a>
                            </td>
                        </tr>
                    @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </div>
@stop

@section('scripts')
    <script>
        $(function() {
            $("#tags-table").DataTable({
            });
        });
    </script>
@stop

注意:在上面的代碼片斷中咱們運用了fontawesome和DataTable 能夠自行用Bower和Gulp集成一下ui

 


3 建立Tag

在咱們進入到建立視圖是須要自動填入一些默認值,能夠這麼作:在TagController裏添加一個屬性fields數組:this

    protected $fields = [
        'tag' => '',
        'title' => '',
        'subtitle' => '',
        'meta_description' => '',
        'page_image' => '',
        'layout' => 'blog.layouts.index',
        'reverse_direction' => 0,
    ];

而後在create方法中運用:spa

    public function create()
    {
        $data = [];
        foreach ($this->fields as $field => $default) {
            // 這裏使用old方法是由於若是驗證規則沒有經過的話 將以前填入的值返回給頁面
            // 這樣就避免了一個問題:某個字段沒有經過規則要求 重定向回建立頁面時以前填入的數據不會消失。
            $data[$field] = old($field, $default);
        }
        return view('admin.tag.create', $data);
    }

建立 create.blade.php 路徑是:views/admin/tagcode

@extends('admin.layout')
@section('content')
<div class="container-fluid">
    <div class="row page-title-row">
        <div class="col-md-12">
            <h3>Tags <small>Create New Tag</small></h3>
        </div>
    </div>
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title">New Tag From</h3>
                </div>
                <div class="panel-body">
                    @include('admin.partials.error')
                    <form action="/admin/tag" method="post" role="form" class="form-horizontal">
                        <input type="hidden" name="_token" value="{{ csrf_token() }}">
                        <div class="form-group">
                            <label for="tag" class="col-md-3 control-label">Tag</label>
                            <div class="col-md-3">
                                <input type="text" class="form-control" name="tag" id="tag" value="{{ $tag }}" autofocus>
                            </div>
                        </div>
                        @include('admin.tag._form')
                        <div class="form-group">
                            <div class="col-md-7 col-md-offset-3">
                                <button class="btn btn-primary btn-md" type="submit">
                                    <i class="fa fa-plus-circle"></i>
                                    Add New Tag
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

上面的代碼片斷中include一個_form.blade.php 是由於有一段HTML是能夠重複利用的orm

接下來就建立_form.blade.php:

<div class="form-group">
    <label for="title" class="col-md-3 control-label">
        Title
    </label>
    <div class="col-md-8">
        <input type="text" class="form-control" name="title" id="title" value="{{ $title }}">
    </div>
</div>

<div class="form-group">
    <label for="subtitle" class="col-md-3 control-label">
        Subtitle
    </label>
    <div class="col-md-8">
        <input type="text" class="form-control" name="subtitle" id="subtitle" value="{{ $subtitle }}">
    </div>
</div>

<div class="form-group">
    <label for="meta_description" class="col-md-3 control-label">
        Meta Description
    </label>
    <div class="col-md-8">
        <textarea class="form-control" id="meta_description" name="meta_description" rows="3">{{ $meta_description }}</textarea>
    </div>
</div>

<div class="form-group">
    <label for="page_image" class="col-md-3 control-label">
        Page Image
    </label>
    <div class="col-md-8">
        <input type="text" class="form-control" name="page_image" id="page_image" value="{{ $page_image }}">
    </div>
</div>

<div class="form-group">
    <label for="layout" class="col-md-3 control-label">
        Layout
    </label>
    <div class="col-md-4">
        <input type="text" class="form-control" name="layout" id="layout" value="{{ $layout }}">
    </div>
</div>

<div class="form-group">
    <label for="reverse_direction" class="col-md-3 control-label">
        Direction
    </label>
    <div class="col-md-7">
        <label class="radio-inline">
            <input type="radio" name="reverse_direction" id="reverse_direction"
                   @if (! $reverse_direction)
                   checked="checked"
                   @endif
                   value="0">
            Normal
        </label>
        <label class="radio-inline">
            <input type="radio" name="reverse_direction"
                   @if ($reverse_direction)
                   checked="checked"
                   @endif
                   value="1">
            Reversed
        </label>
    </div>
</div>

建立一個Request:

class TagCreateRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        // 咱們能夠直接在rules中作一些驗證處理 這根Validate效果是同樣的
        return [
            'tag' => 'required|unique:tags,tag',
            'title' => 'required',
            'subtitle' => 'required',
            'layout' => 'required',
        ];
    }
}

實現store方法:

    public function store(Requests\TagCreateRequest $request)
    {
        $tag = new Tag();
        foreach (array_keys($this->fields) as $field) {
            $tag->$field = $request->get($field);
        }
        $tag->save();

        return redirect('/admin/tag')->withSuccess('The tag "$tag->tag" was created');
    }

 


4 修改Tag

在TagController中添加以下代碼:

    public function edit($id)
    {
        $tag = Tag::findOrFail($id);
        $data = ['id' => $id];
        foreach (array_keys($this->fields) as $key) {
            $data[$key] = old($key, $tag->$key);
        }
        return view('admin.tag.edit', $data);
    }

建立edit視圖:

@extends('admin.layout')
@section('content')
    <div class="container-fluid">
        <div class="row page-title-row">
            <div class="col-md-12">
                <h3>Tags <small>Edit Tag</small></h3>
            </div>
        </div>
        <div class="row">
            <div class="col-md-8 col-md-offset-2">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h3 class="panel-title">Tag Edit Form</h3>
                    </div>
                    <div class="panel-body">
                        @include('admin.partials.error')
                        @include('admin.partials.success')
                        <form action="/admin/tag/{{ $id }}" class="form-horizontal" role="form" method="post">
                            <input type="hidden" name="_token" value="{{ csrf_token() }}">
                            <input type="hidden" name="id" value="{{ $id }}">
                            <input type="hidden" name="_method" value="put">
                            <div class="form-group">
                                <label for="tag" class="col-md-3 control-label">Tag</label>
                                <div class="col-md-3">
                                    <p class="form-control-static">{{ $tag }}</p>
                                </div>
                            </div>
                            @include('admin.tag._form')
                            <div class="form-group">
                                <div class="col-md-7 col-md-offset-3">
                                    <button class="btn btn-primary btn-md" type="submit">
                                        <i class="fa fa-save"></i>
                                        Save Changes
                                    </button>
                                    <button class="btn btn-danger btn-md" type="button" data-toggle="modal" data-target="#modal-delete">
                                        <i class="fa fa-times-circle"></i>
                                        Delete
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="modal-delete" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button class="close" type="button" data-dismiss="modal">x</button>
                    <h4 class="modal-title">Please Confirm</h4>
                </div>
                <div class="modal-body">
                    <p class="lead">
                        <i class="fa fa-question-circle"></i>
                        Are you sure you want to delete this tag?
                    </p>
                </div>
                <div class="modal-footer">
                    <form action="/admin/tag/{{ $id }}" method="post">
                        <input type="hidden" name="_token" value="{{ csrf_token() }}">
                        <input type="hidden" name="_method" value="delete">
                        <button class="btn btn-default" data-dismiss="modal" type="button">Cancl</button>
                        <button class="btn btn-danger" type="submit">
                            <i class="fa fa-times-circle"></i>
                            Yes
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>
@endsection

一樣的 咱們須要建立一個TagUpdateRequest:

class TagUpdateRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title' => 'required',
            'subtitle' => 'required',
            'layout' => 'required',
        ];
    }
}

而後在update方法中添加以下代碼:

    public function update(Request $request, $id)
    {
        $tag = Tag::findOrFail($id);
        foreach (array_keys(array_except($this->fields, ['tag'])) as $field) {
            $tag->$field = $request->get($field);
        }
        $tag->save();
        return redirect("/admin/tag/$id/edit")->withSuccess('Changes saved.');
    }

 


5 刪除Tag

咱們在edit視圖中添加了刪除的表單 如今只須要實現如下TagController中的destroy方法就能夠了:

    public function destroy($id)
    {
        $tag = Tag::findOrFail($id);
        $tag->delete();

        return redirect('/admin/tag')->withSuccess("The '$tag->tag' tag has been deleted.");
    }

 


6 其餘

咱們不須要實現show方法,所以咱們須要把路由改爲這樣:

Route::resource('tag', 'TagController', ['except' => 'show']);

而後刪除TagController中的show方法就好了。

相關文章
相關標籤/搜索