Laravel 5 框架入门(四)完结篇
Laravel  /  管理员 发布于 8年前   220
Page 和评论将使用 Eloquent 提供的“一对多关系”。最终,我们将得到一个个人博客系统的雏形,并布置一个大作业,供大家实战练习。 1. 初识 Eloquent Laravel Eloquent ORM 是 Laravel 中非常重要的部分,也是 Laravel 能如此流行的原因之一。中文文档在: 1. http://laravel-china.org/docs/5.0/eloquent 2. http://www.golaravel.com/laravel/docs/5.0/eloquent/ 在前面的教程中已经建立好的 learnlaravel5/app/Page.php 就是一个 Eloquent Model 类: 若想进一步了解 Eloquent,推荐阅读系列文章:深入理解 Laravel Eloquent 2. 创建 Comment 模型 首先我们要新建一张表来存储 Comment,命令行运行: 成功以后,修改 migration 文件 learnlaravel5/database/migrations/***_create_comments_table.php 的相应位置为: 之后运行: 去数据库里瞧瞧,comments 表已经躺在那儿啦。 3. 建立“一对多关系” 修改 Page 模型: 搞定啦~ Eloquent 中模型间关系就是这么简单。 模型间关系中文文档:http://laravel-china.org/docs/5.0/eloquent#relationships 4. 前台提交功能 修改 Comment 模型: 增加一行路由: 运行以下命令创建 CommentsController 控制器: 修改 CommentsController: 修改视图 learnlaravel5/resources/views/pages/show.blade.php: {{ $page->body }}
php artisan make:model CommentSchema::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 migratehasMany('App\Comment', 'page_id', 'id'); }}
Route::post('comment/store', 'CommentsController@store');
php artisan make:controller CommentsControllerwithInput()->withErrors('评论发表失败!'); } }}
@extends('_layouts.default')@section('content')
⬅️返回首页
{{ $page->title }}
@foreach ($errors->all() as $error)- {{ $error }}
@endforeach
@endif