热搜:NVER node 开发 php

Laravel5.0学习02 实例进阶

2024-07-23 17:05:02
Laravel5.0学习02 实例进阶

本文以laravel5.0.22为例。

本节以新建一个简单的博客作为实例。

准备工作

数据库配置

.env文件(也可以直接修改config/database.php)

DB_HOST=localhostDB_DATABASE=myblogDB_USERNAME=rootDB_PASSWORD=123456

数据库表:

CREATE TABLE `blog` (                                    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,         `uid` int(11) NOT NULL DEFAULT '0',                    `title` varchar(50) NOT NULL DEFAULT '',               `content` text NOT NULL,                               `flag` tinyint(2) NOT NULL DEFAULT '1',                `create_time` int(11) NOT NULL DEFAULT '0',            `update_time` int(11) NOT NULL DEFAULT '0',            PRIMARY KEY (`id`)                                   ) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8  

开始

这里暂时不使用Eloquent ORM,直接使用DB类。

控制器

新建一个控制器:app/Http/Controllers/BlogController.php

<?phpnamespace App\Http\Controllers;use Illuminate\Support\Facades\DB;/** * * @author YJC *         */class BlogController extends Controller{        public function index() {                $list = DB::table('blog')->get();                //需要return        return view('blog.index', ['list' => $list]);    }}

视图

新建一个母版视图:resources/views/blog/layout.blade.php

                Laravel            @yield('content')            

新建一个普通视图:resources/views/blog/index.blade.php

@extends('blog.layout')@section('content')    @foreach($list as $blog)                  

{{$blog->title}}

{{$blog->content}}

@endforeach@endsection

路由

Route::get('blog', 'BlogController@index');

访问

http://localhost/laravel5/public/index.php/blog

即可。

路由技巧

默认的,每新增一个方法,需要写一条路由,比较繁琐。Laravel支持针对一个控制器里所有方法仅写一条路由。需要遵循的规则是:
1) 控制器里方法必须以get、post开头。
2) Route::get()改成Route::controller()。

示例:上面的index方法我们需要改成getIndex,路由这样写:

Route::controller('blog', 'BlogController');

这样,Blog控制器所有的方法都能被路由匹配。例如,有如下方法:

public function getIndex(){}public function getDetail(){}public function postAdd(){}

都可以被匹配。访问的时候直接:

http://localhost/laravel5/public/index.php/blog/indexhttp://localhost/laravel5/public/index.php/blog/detail/2http://localhost/laravel5/public/index.php/blog/add

新增文章详情页

控制器新增getDetail()方法:

public function getDetail($id) {    $blog = DB::table('blog')->find($id);        return view('blog.detail', ['blog' => $blog]);}

更改index.blade.php:

@extends('blog.layout')@section('content')    @foreach($list as $blog)                  

id)}}">{{$blog->title}}

{{$blog->content}}

@endforeach @endsection

新增文章详情试图页detail.blade.php:

@extends('blog.layout')@section('content')          

{{$blog->title}}

{{$blog->content}}

@endsection

更改路由:

//对应blog/indexRoute::get('blog', 'BlogController@index'); //对应blog里任何方法,注意方法要加get或者postRoute::controller('blog', 'BlogController');

使用Eloquent ORM

上面我们一直用的是DB类。接下来我们将使用Eloquent ORM代替DB类。

Laravel 的 Eloquent ORM 提供了更优雅的ActiveRecord 实现来和数据库的互动。 每个数据库表对应一个模型文件。

模型(Model)

在app下新建Blog.php:

<?phpnamespace App;use Illuminate\Database\Eloquent\Model;/**  * @author YJC *  */class Blog extends Model{        //指定表名,不指定系统会默认自动对应名称为「类名称的小写复数形态」的数据库表    protected $table = 'blog';        //指定主键,默认就是id    protected $primaryKey = 'id';        //默认情况下,在数据库表里需要有 updated_at 和 created_at 两个字段。如果您不想设定或自动更新这两个字段,则将类里的 $timestamps 属性设为 false即可    public $timestamps = false;    }

提示:所有DB类里查询构造器里的方法,查询 Eloquent 模型时也可以使用。

控制器里使用模型

复制BlogController.php为BlogController.php.bak,清空原BlogController.php里面内容,改为如下内容:

<?phpnamespace App\Http\Controllers;//需要use模型use App\Blog;/** * * @author YJC *         */class BlogController extends Controller{        public function index() {                $list = Blog::all();                return view('blog.index', ['list' => $list]);    }        public function getDetail($id) {        $blog = Blog::find($id);                return view('blog.detail', ['blog' => $blog]);    }}

Eloquent ORM提供了很多易用的方法来操作数据库。例如:

在Blog.php模型文件里,我们可以使用以下查询方法(Eloquent ORM同时支持$this和静态方式调用):

//取出所有记录,all()得出的是对象集合,可以遍历$this->all()->toArray();//根据主键取出一条数据$one = $this->find('2');return array(  $one->id,  $one->title,  $one->content,);//查找id=2的第一条数据$this->where('id', 2)->first()->toArray();//查找id>0的所有数据$this->where('id', '>', '0')->get()->toArray();//查找id>0的所有数据,降序排列$this->where('id', '>', '0')->orderBy('id', 'desc')->get()->toArray();//查找id>0的所有数据,降序排列,计数$this->where('id', '>', '0')->orderBy('id', 'desc')->count();//offset,limit$this->where('id', '>', '0')->orderBy($order[0], $order[1])->skip($offset)->take($limit);//等同于$this->where('id', '>', '0')->orderBy($order[0], $order[1])->offset($offset)->limit($limit);

更多操作方法详见:http://www.golaravel.com/laravel/docs/5.0/eloquent/

访问http://localhost/laravel5/public/index.php/blog页面看看吧!