您的位置:首页 > 编程语言 > PHP开发

laravel5模型、控制器、视图基本操作

2016-07-11 21:30 771 查看
1、准备工作

1.1、下载好laravel5.1

1.2、创建数据库及表
--
-- 数据库: `myblog`
--

-- --------------------------------------------------------

--
-- 表的结构 `news`
--

CREATE TABLE IF NOT EXISTS `news` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`content` text NOT NULL,
`uid` int(11) NOT NULL DEFAULT '0',
`username` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=6 ;

--
-- 转存表中的数据 `news`
--

INSERT INTO `news` (`id`, `title`, `content`, `uid`, `username`) VALUES
(1, '新闻1', '新闻1内容', 0, '聪哥'),
(2, '新闻2', '新闻2内容', 0, '聪哥'),
(3, '新闻3', '新闻3内容', 0, '聪哥'),
(4, '新闻4', '新闻4内容', 0, '聪哥'),
(5, '新闻5', '新闻5内容', 0, '聪哥');


1.3、修改数据库配置文件

目录下的.env文件

DB_HOST=localhost
DB_DATABASE=myblog
DB_USERNAME=root
DB_PASSWORD=xxxxxxxx

2、添加路由 app\Http\routes.php

Route::get('news', 'NewsController@index');
Route::get('news/detail/{id}', 'NewsController@detail');

3、创建控制器 app\Http\Controllers\NewsController.php
<?php
namespace App\Http\Controllers;
use App\News;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class NewsController extends Controller {
public function index() {
$news = News::all();
//return $news;//直接返回json
return view('news.index', compact('news')); //返回视图

}
public function detail($id) {
//$row = News::findOrFail($id);
$row = News::getOne($id);
return view('news.detail', compact('row'));
}
}


4、创建模型 app\News.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use DB;
class News extends Model {
//use SoftDeletes;
static function getOne($id) {
$row = DB::table('news')->where('id', $id)->first();
//$row = DB::select("SELECT * FROM news WHERE id='$id'");
return $row;
}
}<strong>
</strong>


5、创建视图,laravel使用的是Blade模板引擎,同时也支持php原生写法

resources\views\news\index.blade.php
<html>
<head>
<title>新闻列表</title>
</head>
<body>
<h2>新闻列表</h2>
<div class="container">
@foreach($news as $row)
<article>
<a href="{{url('news/detail/'.$row->id)}}">{{$row->title}}</a>
</article>
@endforeach

</div>
</body>
</html>
resources\views\news\detail.blade.php
<html>
<head>
<title>新闻详情</title>
</head>
<body>
<h2>新闻详情</h2>
<div class="container">
<p>标题:{{$row->title}}</p>
<p>内容:{{$row->content}}</p>
<p>投稿人:{{$row->username}}</p>
</div>
</body>
</html>


6、测试:





推荐个laravel5.1手册:http://laravelacademy.org/post/79.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: