1. 程式人生 > >Laravel5.1 搭建博客 --構建標簽

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

dia field 使用 authorize endif mps prot btn tof

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

在我們之前的筆記中創建了Tag的控制器和路由了 所以這篇筆記不在重復


1 創建模型與遷移文件

遷移文件如下:

    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/tag

@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集成一下


3 創建Tag

在我們進入到創建視圖是需要自動填入一些默認值,可以這麽做:在TagController裏添加一個屬性fields數組:

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

然後在create方法中運用:

    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/tag

@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是可以重復利用的

接下來就創建_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方法就行了。

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