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

4 篇文章 0 订阅

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














  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值