search
HomeBackend DevelopmentPHP TutorialLaravel5.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页面看看吧!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment