欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-04-19 23:33:09
page 和评论将使用 eloquent 提供的“一对多关系”。最终,我们将得到一个个人博客系统的雏形,并布置一个大作业,供大家实战练习。 1. 初识 eloquent...

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

1. 初识 eloquent

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

1.

2.

在前面的教程中已经建立好的 learnlaravel5/app/page.php 就是一个 eloquent model 类:

<?php namespace app;

use illuminate\database\eloquent\model;

class page extends 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 模型:

<?php namespace app;

use illuminate\database\eloquent\model;

class page extends model {

 public function hasmanycomments()
 {
  return $this->hasmany('app\comment', 'page_id', 'id');
 }

}

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

模型间关系中文文档:

4. 前台提交功能

修改 comment 模型:

<?php namespace app;

use illuminate\database\eloquent\model;

class comment extends model {

 protected $fillable = ['nickname', 'email', 'website', 'content', 'page_id'];

}

增加一行路由:

复制代码 代码如下:

route::post('comment/store', 'commentscontroller@store');

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

复制代码 代码如下:

php artisan make:controller commentscontroller

修改 commentscontroller:

<?php namespace app\http\controllers;

use app\http\requests;
use app\http\controllers\controller;

use illuminate\http\request;

use redirect, input;

use app\comment;

class commentscontroller extends controller {

 public function store()
 {
 if (comment::create(input::all())) {
  return redirect::back();
 } else {
  return redirect::back()->withinput()->witherrors('评论发表失败!');
 }

 }

}

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

@extends('_layouts.default')

@section('content')
 <h4>
  <a href="/">⬅️返回首页</a>
 </h4>

 <h1 style="text-align: center; margin-top: 50px;">{{ $page->title }}</h1>
 <hr>
 <div id="date" style="text-align: right;">
  {{ $page->updated_at }}
 </div>
 <div id="content" style="padding: 50px;">
  <p>
   {{ $page->body }}
  </p>
 </div>
 <div id="comments" style="margin-bottom: 100px;">

  @if (count($errors) > 0)
   <div class="alert alert-danger">
    <strong>whoops!</strong> there were some problems with your input.<br><br>
    <ul>
     @foreach ($errors->all() as $error)
      <li>{{ $error }}</li>
     @endforeach
    </ul>
   </div>
  @endif

  <div id="new">
   <form action="{{ url('comment/store') }}" method="post">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <input type="hidden" name="page_id" value="{{ $page->id }}">
    <div class="form-group">
     <label>nickname</label>
     <input type="text" name="nickname" class="form-control" style="width: 300px;" required="required">
    </div>
    <div class="form-group">
     <label>email address</label>
     <input type="email" name="email" class="form-control" style="width: 300px;">
    </div>
    <div class="form-group">
     <label>home page</label>
     <input type="text" name="website" class="form-control" style="width: 300px;">
    </div>
    <div class="form-group">
     <label>content</label>
     <textarea name="content" id="newformcontent" class="form-control" rows="10" required="required"></textarea>
    </div>
    <button type="submit" class="btn btn-lg btn-success col-lg-12">submit</button>
   </form>
  </div>

<script>
function reply(a) {
 var nickname = a.parentnode.parentnode.firstchild.nextsibling.getattribute('data');
 var textarea = document.getelementbyid('newformcontent');
 textarea.innerhtml = '@'+nickname+' ';
}
</script>

  <div class="conmments" style="margin-top: 100px;">
   @foreach ($page->hasmanycomments as $comment)

    <div class="one" style="border-top: solid 20px #efefef; padding: 5px 20px;">
     <div class="nickname" data="{{ $comment->nickname }}">
     @if ($comment->website)
      <a href="{{ $comment->website }}">
       <h3>{{ $comment->nickname }}</h3>
      </a>
     @else
      <h3>{{ $comment->nickname }}</h3>
     @endif
      <h6>{{ $comment->created_at }}</h6>
     </div>
     <div class="content">
      <p style="padding: 20px;">
       {{ $comment->content }}
      </p>
     </div>
     <div class="reply" style="text-align: right; padding: 5px;">
      <a href="#new" onclick="reply(this);">回复</a>
     </div>
    </div>

   @endforeach
  </div>
 </div>
@endsection

前台评论功能完成。

查看效果:

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

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

5. 后台管理功能

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

<!doctype html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <meta http-equiv="x-ua-compatible" content="ie=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <title>laravel</title>

 <link href="/css/app.css" rel="stylesheet">

 <!-- fonts -->
 <link href='http://fonts.useso.com/css?family=roboto:400,300' rel='stylesheet' type='text/css'>
</head>
<body>
 <nav class="navbar navbar-default">
 <div class="container-fluid">
  <div class="navbar-header">
  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
   <span class="sr-only">toggle navigation</span>
   <span class="icon-bar"></span>
   <span class="icon-bar"></span>
   <span class="icon-bar"></span>
  </button>
  <a class="navbar-brand" href="#">learn laravel 5</a>
  </div>

  <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
  <ul class="nav navbar-nav">
   <li><a href="/admin">后台首页</a></li>
  </ul>
  <ul class="nav navbar-nav">
   <li><a href="/admin/comments">管理评论</a></li>
  </ul>

  <ul class="nav navbar-nav navbar-right">
   @if (auth::guest())
   <li><a href="/auth/login">login</a></li>
   <li><a href="/auth/register">register</a></li>
   @else
   <li class="dropdown">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">{{ auth::user()->name }} <span class="caret"></span></a>
    <ul class="dropdown-menu" role="menu">
    <li><a href="/auth/logout">logout</a></li>
    </ul>
   </li>
   @endif
  </ul>
  </div>
 </div>
 </nav>

 @yield('content')

 <!-- scripts -->
 <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
 <script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script>
</body>
</html>

修改后台路由组(增加了一行):

route::group(['prefix' => 'admin', 'namespace' => 'admin', 'middleware' => 'auth'], function()
{
 route::get('/', 'adminhomecomtroller@index');
 route::resource('pages', 'pagescontroller');
 route::resource('comments', 'commentscontroller');
});

创建 admin\commentscontroller :

复制代码 代码如下:

php artisan make:controller admin/commentscontroller

admin/commentscontroller 要有 查看所有、查看单个、post更改、删除四个接口:

<?php namespace app\http\controllers\admin;

use app\http\requests;
use app\http\controllers\controller;

use illuminate\http\request;

use app\comment;

use redirect, input;

class commentscontroller extends controller {

 public function index()
 {
 return view('admin.comments.index')->withcomments(comment::all());
 }

 public function edit($id)
 {
 return view('admin.comments.edit')->withcomment(comment::find($id));
 }

 public function update(request $request, $id)
 {
 $this->validate($request, [
  'nickname' => 'required',
  'content' => 'required',
 ]);
 if (comment::where('id', $id)->update(input::except(['_method', '_token']))) {
  return redirect::to('admin/comments');
 } else {
  return redirect::back()->withinput()->witherrors('更新失败!');
 }
 }

 public function destroy($id)
 {
 $comment = comment::find($id);
 $comment->delete();

 return redirect::to('admin/comments');
 }

}

接下来创建两个视图:

learnlaravel5/resources/views/admin/comments/index.blade.php:

@extends('app')

@section('content')
<div class="container">
 <div class="row">
  <div class="col-md-10 col-md-offset-1">
   <div class="panel panel-default">
    <div class="panel-heading">管理评论</div>

    <div class="panel-body">

    <table class="table table-striped">
     <tr class="row">
      <th class="col-lg-4">content</th>
      <th class="col-lg-2">user</th>
      <th class="col-lg-4">page</th>
      <th class="col-lg-1">编辑</th>
      <th class="col-lg-1">删除</th>
     </tr>
     @foreach ($comments as $comment)
      <tr class="row">
       <td class="col-lg-6">
        {{ $comment->content }}
       </td>
       <td class="col-lg-2">
        @if ($comment->website)
         <a href="{{ $comment->website }}">
          <h4>{{ $comment->nickname }}</h4>
         </a>
        @else
         <h3>{{ $comment->nickname }}</h3>
        @endif
        {{ $comment->email }}
       </td>
       <td class="col-lg-4">
        <a href="{{ url('pages/'.$comment->page_id) }}" target="_blank">
         {{ app\page::find($comment->page_id)->title }}
        </a>
       </td>
       <td class="col-lg-1">
        <a href="{{ url('admin/comments/'.$comment->id.'/edit') }}" class="btn btn-success">编辑</a>
       </td>
       <td class="col-lg-1">
        <form action="{{ url('admin/comments/'.$comment->id) }}" method="post" style="display: inline;">
         <input name="_method" type="hidden" value="delete">
         <input type="hidden" name="_token" value="{{ csrf_token() }}">
         <button type="submit" class="btn btn-danger">删除</button>
        </form>
       </td>
      </tr>
     @endforeach
    </table>


    </div>
   </div>
  </div>
 </div>
</div>
@endsection

learnlaravel5/resources/views/admin/comments/edit.blade.php:

@extends('app')

@section('content')
<div class="container">
 <div class="row">
  <div class="col-md-10 col-md-offset-1">
   <div class="panel panel-default">
    <div class="panel-heading">编辑评论</div>

    <div class="panel-body">

     @if (count($errors) > 0)
      <div class="alert alert-danger">
       <strong>whoops!</strong> there were some problems with your input.<br><br>
       <ul>
        @foreach ($errors->all() as $error)
         <li>{{ $error }}</li>
        @endforeach
       </ul>
      </div>
     @endif

     <form action="{{ url('admin/comments/'.$comment->id) }}" method="post">
      <input name="_method" type="hidden" value="put">
      <input type="hidden" name="_token" value="{{ csrf_token() }}">
      <input type="hidden" name="page_id" value="{{ $comment->page_id }}">
      nickname: <input type="text" name="nickname" class="form-control" required="required" value="{{ $comment->nickname }}">
      <br>
      email:
      <input type="text" name="email" class="form-control" required="required" value="{{ $comment->email }}">
      <br>
      website:
      <input type="text" name="website" class="form-control" required="required" value="{{ $comment->website }}">
      <br>
      content:
      <textarea name="content" rows="10" class="form-control" required="required">{{ $comment->content }}</textarea>
      <br>
      <button class="btn btn-lg btn-info">提交修改</button>
     </form>

    </div>
   </div>
  </div>
 </div>
</div>
@endsection

后台管理功能完成,查看效果:

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

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

6. 大作业
依赖于 page 的评论功能已经全部完成,个人博客系统雏形诞生。在本系列教程的最后,布置一个大作业:构建出 article 的前后台,并且加上 article 与 comment 的一对多关系,加入评论和评论管理功能。在做这个大作业的过程中,你将会反复地回头去看前面的教程,反复地阅读中文文档,会仔细阅读我的代码,等你完成大作业的时候,laravel 5 就真正入门啦~~

以上所述就是本文的全部内容了,希望大家能够喜欢。