Table of Contents
Laravel 5 Framework Getting Started (4) Finale, Laravel Finale
Home Backend Development PHP Tutorial Getting Started with the Laravel 5 Framework (4) Completed Chapter, Laravel Completed Chapter_PHP Tutorial

Getting Started with the Laravel 5 Framework (4) Completed Chapter, Laravel Completed Chapter_PHP Tutorial

Jul 13, 2016 am 09:57 AM
php framework Getting Started Tutorial

Laravel 5 Framework Getting Started (4) Finale, Laravel Finale

Page and comments will use the "one-to-many relationship" provided by Eloquent. In the end, we will get the prototype of a personal blog system and assign a large homework for everyone to practice.

1. First introduction to Eloquent

Laravel Eloquent ORM is a very important part of Laravel and one of the reasons why Laravel is so popular. Chinese documentation is at:

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

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

The learnlaravel5/app/Page.php that has been created in the previous tutorial is an Eloquent Model class:

<&#63;php namespace App;

use Illuminate\Database\Eloquent\Model;

class Page extends Model {

 //

}

Copy after login

If you want to learn more about Eloquent, it is recommended to read this series of articles: In-depth understanding of Laravel Eloquent

2. Create Comment model

First we need to create a new table to store Comments. Run the command line:

Copy code The code is as follows:
php artisan make:model Comment

After success, modify the corresponding location of the migration file learnlaravel5/database/migrations/***_create_comments_table.php to:

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();
});
Copy after login
After

run:

Copy code The code is as follows:
php artisan migrate

Go to the database and take a look. The comments table is already there.

3. Establish a "one-to-many relationship"

Modify Page model:

<&#63;php namespace App;

use Illuminate\Database\Eloquent\Model;

class Page extends Model {

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

}

Copy after login

Done~ The relationship between models in Eloquent is so simple.

Chinese documentation of relationships between models: http://laravel-china.org/docs/5.0/eloquent#relationships

4. Front desk submission function

Modify Comment model:

<&#63;php namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model {

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

}

Copy after login

Add a line of routing:

Copy code The code is as follows:
Route::post('comment/store', 'CommentsController@store');

Run the following command to create the CommentsController controller:

Copy code The code is as follows:
php artisan make:controller CommentsController

Modify CommentsController:

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

 }

}

Copy after login

Modify the view learnlaravel5/resources/views/pages/show.blade.php:

@extends('_layouts.default')

@section('content')
 <h4>
  <a href="/">&#11013;&#65039;返回首页</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

Copy after login

The front desk comment function is completed.

View the effect:

5. Backend management function

Modify the base view learnlaravel5/resources/views/app.blade.php to:

<!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&#63;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>

Copy after login

Modify the background routing group (added a line):

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

Create AdminCommentsController:

Copy code The code is as follows:
php artisan make:controller Admin/CommentsController

Admin/CommentsController must have four interfaces: view all, view single, POST change, and delete:

<&#63;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');
 }

}

Copy after login

Next create two views:

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

Copy after login

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

Copy after login

The background management function is completed, check the effect:

6. Big homework
The comment functions that rely on Page have been completed, and the prototype of the personal blog system was born. At the end of this series of tutorials, a big assignment is assigned: build the front and backend of Article, add a one-to-many relationship between Article and Comment, and add comments and comment management functions. In the process of doing this big assignment, you will go back to the previous tutorials repeatedly, read the Chinese documentation repeatedly, and read my code carefully. By the time you complete the big assignment, you will really get started with Laravel 5~~

The above is the entire content of this article, I hope you all like it.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/981345.htmlTechArticleLaravel 5 Framework Getting Started (4) Finale, Laravel Finale Page and comments will use the "pair" provided by Eloquent Many relationships”. Finally, we will get the prototype of a personal blog system...
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
Comparison of the advantages and disadvantages of PHP frameworks: Which one is better? Comparison of the advantages and disadvantages of PHP frameworks: Which one is better? Jun 04, 2024 pm 03:36 PM

The choice of PHP framework depends on project needs and developer skills: Laravel: rich in features and active community, but has a steep learning curve and high performance overhead. CodeIgniter: lightweight and easy to extend, but has limited functionality and less documentation. Symfony: Modular, strong community, but complex, performance issues. ZendFramework: enterprise-grade, stable and reliable, but bulky and expensive to license. Slim: micro-framework, fast, but with limited functionality and a steep learning curve.

Performance differences of PHP frameworks in different development environments Performance differences of PHP frameworks in different development environments Jun 05, 2024 pm 08:57 PM

There are differences in the performance of PHP frameworks in different development environments. Development environments (such as local Apache servers) suffer from lower framework performance due to factors such as lower local server performance and debugging tools. In contrast, a production environment (such as a fully functional production server) with more powerful servers and optimized configurations allows the framework to perform significantly better.

PHP Frameworks and Microservices: Cloud Native Deployment and Containerization PHP Frameworks and Microservices: Cloud Native Deployment and Containerization Jun 04, 2024 pm 12:48 PM

Benefits of combining PHP framework with microservices: Scalability: Easily extend the application, add new features or handle more load. Flexibility: Microservices are deployed and maintained independently, making it easier to make changes and updates. High availability: The failure of one microservice does not affect other parts, ensuring higher availability. Practical case: Deploying microservices using Laravel and Kubernetes Steps: Create a Laravel project. Define microservice controllers. Create Dockerfile. Create a Kubernetes manifest. Deploy microservices. Test microservices.

Integration of PHP frameworks with DevOps: the future of automation and agility Integration of PHP frameworks with DevOps: the future of automation and agility Jun 05, 2024 pm 09:18 PM

Integrating PHP frameworks with DevOps can improve efficiency and agility: automate tedious tasks, free up personnel to focus on strategic tasks, shorten release cycles, accelerate time to market, improve code quality, reduce errors, enhance cross-functional team collaboration, and break down development and operations silos

The best PHP framework for microservice architecture: performance and efficiency The best PHP framework for microservice architecture: performance and efficiency Jun 03, 2024 pm 08:27 PM

Best PHP Microservices Framework: Symfony: Flexibility, performance and scalability, providing a suite of components for building microservices. Laravel: focuses on efficiency and testability, provides a clean API interface, and supports stateless services. Slim: minimalist, fast, provides a simple routing system and optional midbody builder, suitable for building high-performance APIs.

Which PHP framework offers the most comprehensive extension library for rapid development? Which PHP framework offers the most comprehensive extension library for rapid development? Jun 04, 2024 am 10:45 AM

The PHP framework extension library provides four frameworks for selection: Laravel: Known for its vast ecosystem and third-party packages, it provides authentication, routing, validation and other extensions. Symfony: Highly modular, extending functionality through reusable "Bundles", covering areas such as authentication and forms. CodeIgniter: lightweight and high-performance, providing practical extensions such as database connection and form validation. ZendFramework: Powerful enterprise-level features, with extensions such as authentication, database connection, RESTfulAPI support, etc.

The application potential of artificial intelligence in PHP framework The application potential of artificial intelligence in PHP framework Jun 03, 2024 am 11:01 AM

The application potential of Artificial Intelligence (AI) in PHP framework includes: Natural Language Processing (NLP): for analyzing text, identifying emotions and generating summaries. Image processing: used to identify image objects, face detection and resizing. Machine learning: for prediction, classification and clustering. Practical cases: chatbots, personalized recommendations, fraud detection. Integrating AI can enhance website or application functionality, providing powerful new features.

PHP Frameworks and Artificial Intelligence: A Developer's Guide PHP Frameworks and Artificial Intelligence: A Developer's Guide Jun 04, 2024 pm 12:47 PM

Use a PHP framework to integrate artificial intelligence (AI) to simplify the integration of AI in web applications. Recommended framework: Laravel: lightweight, efficient, and powerful. CodeIgniter: Simple and easy to use, suitable for small applications. ZendFramework: Enterprise-level framework with complete functions. AI integration method: Machine learning model: perform specific tasks. AIAPI: Provides pre-built functionality. AI library: handles AI tasks.

See all articles