Home > Backend Development > PHP Tutorial > Laravel 5 框架入门!!!

Laravel 5 框架入门!!!

PHPz
Release: 2021-05-31 16:11:33
forward
2564 people have browsed it

本文,我们将一起给 Page 加入评论功能,让用户在前台页面可以查看、提交、回复评论,同时我们将在后台完善评论管理功能,可以删除、编辑评论。

Laravel 5 框架入门!!!

1. 初识 Eloquent

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

  •  http://laravel-china.org/docs/5.0/eloquent

  • http://www.golaravel.com/laravel/docs/5.0/eloquent/

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

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Page extends Model {

 //

}
Copy after login

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

2. 创建 Comment 模型

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

代码如下:

php artisan make:model Comment
Copy after login

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

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

之后运行:

代码如下:

php artisan migrate
Copy after login

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

3. 建立“一对多关系”

修改 Page 模型:

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Page extends Model {

 public function hasManyComments()
 {
  return $this->hasMany(&#39;App\Comment&#39;, &#39;page_id&#39;, &#39;id&#39;);
 }

}
Copy after login

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

模型间关系中文文档:http://laravel-china.org/docs/5.0/eloquent#relationships

4. 前台提交功能

修改 Comment 模型:

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model {

 protected $fillable = [&#39;nickname&#39;, &#39;email&#39;, &#39;website&#39;, &#39;content&#39;, &#39;page_id&#39;];

}
Copy after login

增加一行路由:

代码如下:

Route::post(&#39;comment/store&#39;, &#39;CommentsController@store&#39;);
Copy after login

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

代码如下:

php artisan make:controller CommentsController
Copy after login

修改 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(&#39;评论发表失败!&#39;);
 }

 }

}
Copy after login

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

@extends(&#39;_layouts.default&#39;)

@section(&#39;content&#39;)
 <h4>
  <a href="/">⬅️返回首页</a>
 </h4>

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

  @if (count($errors) > 0)
   <p 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>
   </p>
  @endif

  <p id="new">
   <form action="{{ URL(&#39;comment/store&#39;) }}" method="POST">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <input type="hidden" name="page_id" value="{{ $page->id }}">
    <p class="form-group">
     <label>Nickname</label>
     <input type="text" name="nickname" class="form-control" style="width: 300px;" required="required">
    </p>
    <p class="form-group">
     <label>Email address</label>
     <input type="email" name="email" class="form-control" style="width: 300px;">
    </p>
    <p class="form-group">
     <label>Home page</label>
     <input type="text" name="website" class="form-control" style="width: 300px;">
    </p>
    <p class="form-group">
     <label>Content</label>
     <textarea name="content" id="newFormContent" class="form-control" rows="10" required="required"></textarea>
    </p>
    <button type="submit" class="btn btn-lg btn-success col-lg-12">Submit</button>
   </form>
  </p>

<script>
function reply(a) {
 var nickname = a.parentNode.parentNode.firstChild.nextSibling.getAttribute(&#39;data&#39;);
 var textArea = document.getElementById(&#39;newFormContent&#39;);
 textArea.innerHTML = &#39;@&#39;+nickname+&#39; &#39;;
}
</script>

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

    <p class="one" style="border-top: solid 20px #efefef; padding: 5px 20px;">
     <p 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>
     </p>
     <p class="content">
      <p style="padding: 20px;">
       {{ $comment->content }}
      </p>
     </p>
     <p class="reply" style="text-align: right; padding: 5px;">
      <a href="#new" onclick="reply(this);">回复</a>
     </p>
    </p>

   @endforeach
  </p>
 </p>
@endsection
Copy after login

前台评论功能完成。

查看效果:

1.jpg

2.jpg

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=&#39;http://fonts.useso.com/css?family=Roboto:400,300&#39; rel=&#39;stylesheet&#39; type=&#39;text/css&#39;>
</head>
<body>
 <nav class="navbar navbar-default">
 <p class="container-fluid">
  <p 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>
  </p>

  <p 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>
  </p>
 </p>
 </nav>

 @yield(&#39;content&#39;)

 <!-- 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>
Copy after login

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

Route::group([&#39;prefix&#39; => &#39;admin&#39;, &#39;namespace&#39; => &#39;Admin&#39;, &#39;middleware&#39; => &#39;auth&#39;], function()
{
 Route::get(&#39;/&#39;, &#39;AdminHomeComtroller@index&#39;);
 Route::resource(&#39;pages&#39;, &#39;PagesController&#39;);
 Route::resource(&#39;comments&#39;, &#39;CommentsController&#39;);
});
Copy after login

创建 Admin\CommentsController :

代码如下:

php artisan make:controller Admin/CommentsController
Copy after login

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(&#39;admin.comments.index&#39;)->withComments(Comment::all());
 }

 public function edit($id)
 {
 return view(&#39;admin.comments.edit&#39;)->withComment(Comment::find($id));
 }

 public function update(Request $request, $id)
 {
 $this->validate($request, [
  &#39;nickname&#39; => &#39;required&#39;,
  &#39;content&#39; => &#39;required&#39;,
 ]);
 if (Comment::where(&#39;id&#39;, $id)->update(Input::except([&#39;_method&#39;, &#39;_token&#39;]))) {
  return Redirect::to(&#39;admin/comments&#39;);
 } else {
  return Redirect::back()->withInput()->withErrors(&#39;更新失败!&#39;);
 }
 }

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

 return Redirect::to(&#39;admin/comments&#39;);
 }

}
Copy after login

接下来创建两个视图:

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

@extends(&#39;app&#39;)

@section(&#39;content&#39;)
<p class="container">
 <p class="row">
  <p class="col-md-10 col-md-offset-1">
   <p class="panel panel-default">
    <p class="panel-heading">管理评论</p>

    <p 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(&#39;pages/&#39;.$comment->page_id) }}" target="_blank">
         {{ App\Page::find($comment->page_id)->title }}
        </a>
       </td>
       <td class="col-lg-1">
        <a href="{{ URL(&#39;admin/comments/&#39;.$comment->id.&#39;/edit&#39;) }}" class="btn btn-success">编辑</a>
       </td>
       <td class="col-lg-1">
        <form action="{{ URL(&#39;admin/comments/&#39;.$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>


    </p>
   </p>
  </p>
 </p>
</p>
@endsection
Copy after login

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

@extends(&#39;app&#39;)

@section(&#39;content&#39;)
<p class="container">
 <p class="row">
  <p class="col-md-10 col-md-offset-1">
   <p class="panel panel-default">
    <p class="panel-heading">编辑评论</p>

    <p class="panel-body">

     @if (count($errors) > 0)
      <p 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>
      </p>
     @endif

     <form action="{{ URL(&#39;admin/comments/&#39;.$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>

    </p>
   </p>
  </p>
 </p>
</p>
@endsection
Copy after login

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

3.jpg

4.jpg

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

推荐学习:《PHP视频教程

Related labels:
source:jb51.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template