Heim  >  Artikel  >  php教程  >  Laravel 5 框架入门(四)完结篇

Laravel 5 框架入门(四)完结篇

WBOY
WBOYOriginal
2016-06-06 20:05:141154Durchsuche

本文是本系列教程的完结篇,我们将一起给 Page 加入评论功能,让游客在前台页面可以查看、提交、回复评论,同时我们将在后台完善评论管理功能,可以删除、编辑评

Page 和评论将使用 Eloquent 提供的“一对多关系”。最终,我们将得到一个个人博客系统的雏形,并布置一个大作业,供大家实战练习。

1. 初识 Eloquent

Laravel Eloquent ORM 是 Laravel 中非常重要的部分,也是 Laravel 能如此流行的原因之一。中文文档在:

1.

2.

在前面的教程中已经建立好的 learnlaravel5/app/Page.php 就是一个 Eloquent Model 类:

若想进一步了解 Eloquent,推荐阅读系列文章:深入理解 Laravel Eloquent

2. 创建 Comment 模型

首先我们要新建一张表来存储 Comment,命令行运行:

复制代码 代码如下:


php artisan make:model Comment

成功以后,修改 migration 文件 learnlaravel5/database/migrations/***_create_comments_table.php 的相应位置为:

Schema::create('comments', function(Blueprint $table) { $table->increments('id'); $table->string('nickname'); $table->string('email')->nullable(); $table->string('website')->nullable(); $table->text('content')->nullable(); $table->integer('page_id'); $table->timestamps(); });

之后运行:

复制代码 代码如下:


php artisan migrate

去数据库里瞧瞧,,comments 表已经躺在那儿啦。

3. 建立“一对多关系”

修改 Page 模型:

hasMany('App\Comment', 'page_id', 'id'); } }

搞定啦~ Eloquent 中模型间关系就是这么简单。

模型间关系中文文档:

4. 前台提交功能

修改 Comment 模型:

增加一行路由:

复制代码 代码如下:


Route::post('comment/store', 'CommentsController@store');

运行以下命令创建 CommentsController 控制器:

复制代码 代码如下:


php artisan make:controller CommentsController

修改 CommentsController:

withInput()->withErrors('评论发表失败!'); } } }

修改视图 learnlaravel5/resources/views/pages/show.blade.php:

@extends('_layouts.default') @section('content')

⬅️返回首页

{{ $page->title }}


{{ $page->updated_at }}

{{ $page->body }}

@if (count($errors) > 0)
Whoops! There were some problems with your input.

    @foreach ($errors->all() as $error)
  • {{ $error }}
  • @endforeach
@endif
<script> function reply(a) { var nickname = a.parentNode.parentNode.firstChild.nextSibling.getAttribute('data'); var textArea = document.getElementById('newFormContent'); textArea.innerHTML = '@'+nickname+' '; } </script>
@foreach ($page->hasManyComments as $comment)
@if ($comment->website)

{{ $comment->nickname }}

@else

{{ $comment->nickname }}

@endif
{{ $comment->created_at }}

{{ $comment->content }}

@endforeach
@endsection

前台评论功能完成。

查看效果:

Laravel 5 框架入门(四)完结篇

Laravel 5 框架入门(四)完结篇

5. 后台管理功能

修改基础视图 learnlaravel5/resources/views/app.blade.php 为:

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn