Home Backend Development PHP Tutorial Laravel 5 框架入门(一)_php实例

Laravel 5 框架入门(一)_php实例

May 16, 2016 pm 08:17 PM
laravel framework

Laravel 5 中文文档:

1. http://laravel-china.org/docs/5.0

2. http://www.golaravel.com/laravel/docs/5.0/

默认条件

本文默认你已经有配置完善的 PHP + MySQL 运行环境,懂得 PHP 网站运行的基础知识。跟随本教程走完一遍,你将会得到一个基础的包含登录的简单 blog 系统,并将学会如何使用一些强大的 Laravel 插件和 composer 包(Laravel 插件也是 composer 包)。

软件版本:PHP 5.4+,MySQL 5.1+

本文不推荐完全不懂 PHP 与 MVC 编程的人学习。本文不是 “一步一步跟我做” 教程。本文需要你付出一定的心智去解决一些或大或小的隐藏任务,以达到真正理解 Laravel 运行逻辑的目的。

1. 安装

许多人被拦在了学习Laravel的第一步,安装。并不是因为安装教程有多复杂,而是因为【众所周知的原因】。在此我推荐一个composer全量中国镜像:http://pkg.phpcomposer.com/ 。推荐以 “修改 composer 的配置文件” 方式配置。

镜像配置完成后,切换到你想要放置该网站的目录下(如 C:\\wwwroot、/Library/WebServer/Documents/、/var/www/html、/etc/nginx/html 等),运行命令:

composer create-project laravel/laravel learnlaravel5
Copy after login

然后,稍等片刻,当前目录下就会出现一个叫 learnlaravel5 的文件夹。

然后将网站根目录配置为 learnlaravel5/public。

如果你不会配置,建议去学会配置,网上资料很多。如果自暴自弃,可以把 的第 29 行'url' => 'http://localhost', 配置成你的子目录地址,注意,要一直配置到 ***/learnlaravel5/public。

使用浏览器访问你配置的地址,将看到以下画面(我在本地配置的地址为 http://fuck.io:88 ):


2. 体验 Auth 系统并完成安装

—— 经过上面的过程,Laravel 5 的安装成功了?

—— 没有o(╯□╰)o

查看路由文件 `learnlaravel5/app/Http/routes.php` 的代码:

Route::get('/', 'WelcomeController@index');

Route::get('home', 'HomeController@index');

Route::controllers([
	'auth' => 'Auth\AuthController',
	'password' => 'Auth\PasswordController',
]);
Copy after login

跟随代码里的蛛丝马迹,让我们访问 http://fuck.io:88/home (请自行替换域名),结果竟然跳转到了登陆页?


没错,Laravel 自带了开箱即用的 Auth 系统,连页面都已经写好了。

让我们随意输入邮箱和密码,点击登录,你很可能得到以下画面(Mac 或 Linux 下):


为什么空白?用开发者工具查看,这个请求的状态码是 500,为什么?

因为 `learnlaravel5/storage` 目录没有 777 权限。

执行 shell 命令:

cd learnlaravel5

sudo chmod -R 777 storage
Copy after login

重新访问 http://fuck.io:88/home ,随意输入邮箱和密码,如果你得到以下画面:


那么恭喜你~ Laravel 5 安装成功!

不想配置镜像的同学,可以使用 Laravel 界非常著名的 安正超 搞的安装神器:https://github.com/overtrue/latest-laravel

3. 数据库建立及迁移

Laravel 5 把数据库配置的地方改到了 `learnlaravel5/.env`,打开这个文件,编辑下面四项,修改为正确的信息:

DB_HOST=localhost

DB_DATABASE=laravel5

DB_USERNAME=root

DB_PASSWORD=password
Copy after login

推荐新建一个名为 laravel5 的数据库,为了学习方便,推荐使用 root 账户直接操作。

Laravel 已经为我们准备好了 Auth 部分的 migration,运行以下命令执行数据库迁移操作:

php artisan migrate
Copy after login
Copy after login

得到的结果如下:


如果你运行命令报错,请检查数据库连接设置。

至此,数据库迁移已完成,你可以打开 http://fuck.io:88/home 欢快地尝试注册、登录啦。

4. 模型 Models

接下来我们将接触Laravel最为强大的部分,Eloquent ORM,真正提高生产力的地方,借用库克的一句话:鹅妹子英!

运行一下命令:

php artisan make:model Article

php artisan make:model Page
Copy after login

> Laravel 4 时代,我们使用 Generator 插件来新建 Model。现在,Laravel 5 已经把 Generator 集成进了 Artisan。

现在,Artisan 帮我们在 `learnlaravel5/app/` 下创建了两个文件 `Article.php` 和 `Page.php`,这是两个 Model 类,他们都继承了 Laravel Eloquent 提供的 Model 类 `Illuminate\Database\Eloquent\Model`,且都在 `\App` 命名空间下。这里需要强调一下,用命令行的方式创建文件,和自己手动创建文件没有任何区别,你也可以尝试自己创建这两个 Model 类。

Model 即为 MVC 中的 M,翻译为 模型,负责跟数据库交互。在 Eloquent 中,数据库中每一张表对应着一个 Model 类(当然也可以对应多个)。

如果你从其他框架转过来,可能对这里一笔带过的 Model 部分很不适应,没办法,是因为 Eloquent 实在太强大了啦,真的没什么好做的,继承一下 Eloquent 类就能实现很多很多功能了。

如果你想深入地了解 Eloquent,可以阅读系列文章:Laravel 5框架学习之Eloquent 关系

接下来进行 Article 和 Page 类对应的 articles 表和 pages表的数据库迁移,进入 `learnlaravel5/database/migrations` 文件夹。

在 ***_create_articles_table.php 中修改:

Schema::create('articles', function(Blueprint $table)
{
	$table->increments('id');
	$table->string('title');
	$table->string('slug')->nullable();
	$table->text('body')->nullable();
	$table->string('image')->nullable();
	$table->integer('user_id');
	$table->timestamps();
});
Copy after login

在 ***_create_pages_table.php 中修改:

Schema::create('pages', function(Blueprint $table)
{
	$table->increments('id');
	$table->string('title');
	$table->string('slug')->nullable();
	$table->text('body')->nullable();
	$table->integer('user_id');
	$table->timestamps();
});
Copy after login

然后执行命令:

php artisan migrate
Copy after login
Copy after login

成功以后, tables 表和 pages 表已经出现在了数据库里,去看看吧~

5. 数据库填充 Seeder

在 `learnlaravel5/database/seeds/` 下新建 `PageTableSeeder.php` 文件,内容如下:

<&#63;php

use Illuminate\Database\Seeder;
use App\Page;

class PageTableSeeder extends Seeder {

 public function run()
 {
  DB::table('pages')->delete();

  for ($i=0; $i < 10; $i++) {
   Page::create([
    'title'  => 'Title '.$i,
    'slug'  => 'first-page',
    'body'  => 'Body '.$i,
    'user_id' => 1,
   ]);
  }
 }

}
Copy after login

然后修改同一级目录下的 `DatabaseSeeder.php`中:

// $this->call('UserTableSeeder');
Copy after login

这一句为

$this->call('PageTableSeeder');
Copy after login

然后运行命令进行数据填充:

composer dump-autoloadphp artisan db:seed
Copy after login

去看看 pages 表,是不是多了十行数据?

本教程示例代码见:https://github.com/johnlui/Learn-Laravel-5

大家在任何地方卡住,最快捷的解决方式就是去看我的示例代码。

以上所述就是本文的全部内容了,希望能够对大家学习Laravel5框架有所帮助。

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

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.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

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 debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

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

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

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...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

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�...

See all articles