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
<!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 rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css"></head><body> @yield('content') <!-- Scripts --> <script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script> <script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script></body></html>
新建一个普通视图:resources/views/blog/index.blade.php
@extends('blog.layout')@section('content') @foreach($list as $blog) <div> <h1 id="blog-title">{{$blog->title}}</h1> <p>{{$blog->content}}</p> </div> @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) <div> <h1 id="a-href-url-blog-detail-blog-id-blog-title-a"><a href="{{url('blog/detail/'.$blog->id)}}">{{$blog->title}}</a></h1> <p>{{$blog->content}}</p> </div> @endforeach @endsection
新增文章详情试图页detail.blade.php:
@extends('blog.layout')@section('content') <div class="jumbotron"> <h1 id="blog-title">{{$blog->title}}</h1> <p>{{$blog->content}}</p> </div>@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页面看看吧!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...
