Laravel 5 系列入门教程(一)【最适合中国人的 Laravel 教程】
基于最新 Laravel 5.5 的 2017 版教程已经发布到 Github:https://github.com/johnlui/Learn-Laravel-5/issues
十分建议学习 5.5,跟 5.0 比变化非常大。
本教程示例代码见:https://github.com/johnlui/Learn-Laravel-5
大家在任何地方卡住,最快捷的解决方式就是去看我的示例代码。
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 5.0.22
然后,稍等片刻,当前目录下就会出现一个叫 learnlaravel5 的文件夹。
本系列教程使用 Laravel 5.0 版本,5.1 版本去掉了本系列教程主要讲解的元素(Auth 系统),不建议使用 5.1 来学习。本系列教程为入门教程,目的是搞清楚 Laravel 的基本使用方法,切忌本末倒置。
如果你不会配置,建议去学会配置,网上资料很多。如果自暴自弃,可以把 的第 29 行 'url' => 'http://localhost', 配置成你的子目录地址,注意,要一直配置到 */learnlaravel5/public。然后将网站根目录配置为 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', ]);
跟随代码里的蛛丝马迹,让我们访问 http://fuck.io:88/home (请自行替换域名),结果竟然跳转到了登陆页?
没错,Laravel 自带了开箱即用的 Auth 系统,连页面都已经写好了。
让我们随意输入邮箱和密码,点击登录,你很可能得到以下画面(Mac 或 Linux 下):
为什么空白?用开发者工具查看,这个请求的状态码是 500,为什么?
因为
learnlaravel5/storage
目录没有 777 权限。
执行 shell 命令:
cd learnlaravel5 sudo chmod -R 777 storage
重新访问 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
推荐新建一个名为 laravel5 的数据库,为了学习方便,推荐使用 root 账户直接操作。
Laravel 已经为我们准备好了 Auth 部分的 migration,运行以下命令执行数据库迁移操作:
php artisan migrate
得到的结果如下:
如果你运行命令报错,请检查数据库连接设置。
至此,数据库迁移已完成,你可以打开 http://fuck.io:88/home 欢快地尝试注册、登录啦。
4. 模型 Models
接下来我们将接触Laravel最为强大的部分,Eloquent ORM,真正提高生产力的地方,借用库克的一句话:鹅妹子英!
运行一下命令:
php artisan make:model Article php artisan make:model Page
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 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(); });
在 *_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(); });
然后执行命令:
php artisan migrate
成功以后, articles 表和 pages 表已经出现在了数据库里,去看看吧~
5. 数据库填充 Seeder
在 learnlaravel5/database/seeds/
下新建 PageTableSeeder.php
文件,内容如下:
delete(); for ($i=0; $i < 10; $i++) { Page::create([ 'title' => 'Title '.$i, 'slug' => 'first-page', 'body' => 'Body '.$i, 'user_id' => 1, ]); } } }
然后修改同一级目录下的 DatabaseSeeder.php
中:
// $this->call('UserTableSeeder');
这一句为
$this->call('PageTableSeeder');
然后运行命令进行数据填充:
composer dump-autoload php artisan db:seed
去看看 pages 表,是不是多了十行数据?
教程(一)代码快照:https://github.com/johnlui/Learn-Laravel-5/archive/tutorial_1.zip
下一步:Laravel 5 系列入门教程(二)【最适合中国人的 Laravel 教程】
评论:
2015-09-23 12:53
我 composer update了
但运行还是Whoops, looks like something went wrong.
1/1 FatalErrorException in routes.php line 15: Call to undefined method Illuminate\Routing\Route::get()
还有就是 composer update 有什么作用呢
2015-09-23 10:49
我这个 Route::get('/', 'WelcomeController@index');
<?php namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
class WelcomeController extends Controller {
public function index()
{
return View::make('welcome');
}
}
运行时
Whoops, looks like something went wrong.
1/1 FatalErrorException in routes.php line 18: Call to undefined method Illuminate\Routing\Route::get()
我是不是哪里 弄错了
2015-09-21 10:38
DB_DATABASE=laravel5
DB_USERNAME=root
DB_PASSWORD=123456
数据库用户名,密码都改了,执行php artisan migrate报错SQLSTATE[HY000] [1045] Access denied for user ‘homestead’@’localhost’ (using password: YES),homestead这个用户哪来的。。

2015-09-19 16:57
我按教程运行到最后一步的时候
composer dump-autoload
php artisan db:seed
就报错了
[ReflectionException]
Class UserTableSeeder does not exist
请问是哪里的问题?
2015-09-18 15:14
<form action="{{ URL('admin/pages') }}" method="POST">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="text" name="title" class="form-control" required="required">
<br>
<textarea name="body" rows="10" class="form-control" required="required"></textarea>
<br>
<button class="btn btn-lg btn-info">新增 Page</button>
</form>
这个action中并没有指明要调到pages中的哪个方法,为什么会进入store方法,laravel是怎么进行操作的?
2015-09-11 11:23
WenTableSeeder.php
class WenTableSeeder extends Seeder {
public function run()
{
DB::table('wens')->delete();
for ($i=0; $i < 10; $i++) {
Wen::create([
'title' => 'ArticlesTitle '.$i,
'slug' => 'first-article',
'author' => 'Lee '.$i,
'tag' => 'tag '.$i,
'body' => 'My is articles '.$i,
'user_id' => 2,
'image' => 'jpg '.$i,
]);
}
}
}
但是执行php artisan db:seed之后,总会提示这个错误:
Class 'Wen' not found
PHP Fatal error: Class 'Wen' not found in D:\phpStudy\WWW\test\firstpj\database\seeds\WenTableSeeder.php on line 12
不知道该怎处理
2015-09-09 17:57
我想要修改用户的栏位
CREATE TABLE IF NOT EXISTS `users` (
`users_id` int(10) unsigned NOT NULL,
`users_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`users_email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`users_tel` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`users_password` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
`remember_token` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
改了view 也改了Service\Registrar.php 但是还是出现错误
QueryException in Connection.php line 620:
SQLSTATE[HY000]: General error: 1364 Field 'users_name' doesn't have a default value (SQL: insert into `users` (`updated_at`, `created_at`) values (2015-09-09 09:17:41, 2015-09-09 09:17:41))
2015-09-09 18:30
2015-09-07 22:59
http://fuck.io:88 這頁可以出現
但到 http://fuck.io:88/home 則變成404 我不知道我哪做錯了請教教我
(v5.0.22)
2015-09-04 17:02
PagesController.php里面的public function edit只有
return view('admin.pages.edit')->withPage(Page::find($id));这一段代码,并没有看到分配的变量$page。
而且我把edit.blade.php里面的{{ $page->title }}改成{{ ¥pages->title }}后就会提示Undefined variable: pages
这个地方的变量名是在是么地方定义或分配的唷


2015-08-30 20:37
出现这个错误是为什么?我在网上搜索过,但也还是没有找到解决办法。
环境: Ubuntu 14.04
PHP 5.5.9
Apache 2.4.7
2015-08-27 17:55
- Installing laravel/laravel (v5.0.22)
Loading from cache
Created project in laravel
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Your requirements could not be resolved to an installable set of packages.
Problem 1
- Installation request for laravel/framework v5.0.16 -> satisfiable by laravel/framework[v5.0.16].
- laravel/framework v5.0.16 requires ext-mcrypt * -> the requested PHP extension mcrypt is missing from your system.
照旧啊。。。
2015-09-14 15:58
Installing laravel/laravel (v5.0.22)
- Installing laravel/laravel (v5.0.22)
Loading from cache
Created project in laravel
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Your requirements could not be resolved to an installable set of packages.
Problem 1
- Installation request for laravel/framework v5.0.16 -> satisfiable by laravel/framework[v5.0.16].
- laravel/framework v5.0.16 requires ext-mcrypt * -> the requested PHP extension mcrypt is missing from your system.
2015-08-27 17:29
- Installation request for laravel/framework v5.0.16 -> satisfiable by laravel/framework[v5.0.16].
- laravel/framework v5.0.16 requires ext-mcrypt * -> the requested PHP extension mcrypt is missing from your system.
mac下报这个错误,mcrypt在phpinfo可以看见的
2015-08-27 18:07
mcrypt support => enabled
mcrypt_filter support => enabled
Version => 2.5.8
Api No => 20021217
Supported ciphers => cast-128 gost rijndael-128 twofish arcfour cast-256 loki97 rijndael-192 saferplus wake blowfish-compat des rijndael-256 serpent xtea blowfish enigma rc2 tripledes
Supported modes => cbc cfb ctr ecb ncfb nofb ofb stream
php-fpm -i查看的信息,没问题啊。
2015-09-05 13:46
cd ~
vim ./bash_profile
添加一行
export PATH=/Applications/MAMP/bin/php/php5.4.10/bin:$PATH
保存退出
source .bash_profile
然后which php 看变化 ,现在安装应该没啥问 我今天刚遇到, laravel5新手!
2015-08-26 09:35

2015-08-25 00:36
2015-08-24 14:33
Installing laravel/laravel (v5.0.22)
- Installing laravel/laravel (v5.0.22)
Loading from cache
Created project in laravel
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Your requirements could not be resolved to an installable set of packages.
Problem 1
- Installation request for phpunit/phpunit 4.5.0 -> satisfiable by phpunit/phpunit[4.5.0].
- phpunit/phpunit 4.5.0 requires ext-dom * -> the requested PHP extension dom is missing from your system.
您好,请教一个问题 ,我在linux 安装报错 ,这个,有解决办法吗? 是加dom扩展 吗,但是加上了 没效果。
2015-08-24 16:56
yum install php-xml
Loaded plugins: fastestmirror
Setting up Install Process
Loading mirror speeds from cached hostfile
* base: mirrors.yun-idc.com
* extras: mirrors.btte.net
* remi-safe: mirrors.mediatemple.net
* updates: mirrors.yun-idc.com
Resolving Dependencies
--> Running transaction check
---> Package php-xml.x86_64 0:5.3.3-46.el6_6 will be installed
--> Processing Dependency: php-common(x86-64) = 5.3.3-46.el6_6 for package: php-xml-5.3.3-46.el6_6.x86_64
--> Processing Dependency: libxslt.so.1(LIBXML2_1.0.24)(64bit) for package: php-xml-5.3.3-46.el6_6.x86_64
--> Processing Dependency: libxslt.so.1(LIBXML2_1.0.22)(64bit) for package: php-xml-5.3.3-46.el6_6.x86_64
--> Processing Dependency: libxslt.so.1(LIBXML2_1.0.18)(64bit) for package: php-xml-5.3.3-46.el6_6.x86_64
--> Processing Dependency: libxslt.so.1(LIBXML2_1.0.13)(64bit) for package: php-xml-5.3.3-46.el6_6.x86_64
--> Processing Dependency: libxslt.so.1(LIBXML2_1.0.11)(64bit) for package: php-xml-5.3.3-46.el6_6.x86_64
--> Processing Dependency: libxslt.so.1()(64bit) for package: php-xml-5.3.3-46.el6_6.x86_64
--> Processing Dependency: libexslt.so.0()(64bit) for package: php-xml-5.3.3-46.el6_6.x86_64
--> Running transaction check
---> Package libxslt.x86_64 0:1.1.26-2.el6_3.1 will be installed
---> Package php-xml.x86_64 0:5.3.3-46.el6_6 will be installed
--> Processing Dependency: php-common(x86-64) = 5.3.3-46.el6_6 for package: php-xml-5.3.3-46.el6_6.x86_64
--> Finished Dependency Resolution
Error: Package: php-xml-5.3.3-46.el6_6.x86_64 (updates)
Requires: php-common(x86-64) = 5.3.3-46.el6_6
Installed: php-common-5.5.28-1.el6.remi.x86_64 (@remi-php55)
php-common(x86-64) = 5.5.28-1.el6.remi
Available: php-common-5.3.3-40.el6_6.x86_64 (base)
php-common(x86-64) = 5.3.3-40.el6_6
Available: php-common-5.3.3-46.el6_6.x86_64 (updates)
php-common(x86-64) = 5.3.3-46.el6_6
You could try using --skip-broken to work around the problem
You could try running: rpm -Va --nofiles --nodigest
看的糊涂。
2015-08-23 21:31
php artisan make:model Page会创建在app/Http/Page.php model文件
在 ***_create_pages_table.php 中修改: //为什么会生成pages名的文件而不是 page
Schema::create('pages', function(Blueprint $table) //这里为什么不是page而是pages表
{
$table->increments('id');
$table->string('title');
$table->string('slug')->nullable();
$table->text('body')->nullable();
$table->integer('user_id');
$table->timestamps();
});
2015-09-23 15:14