Laravel 4 系列入门教程(一)【最适合中国人的Laravel教程】
基于最新 Laravel 5.2 的 2016 版教程已经发布到 Github:https://github.com/johnlui/Learn-Laravel-5/issues/4
十分建议学习 5.2,4.2 早已不再维护。
向 Laravel 4 – simple website with backend tutorial – Part 1 致敬,本教程部分内容翻译自此文章。
每一个教程完成,我将会git commit一次。
示例代码见 https://github.com/johnlui/Learn-Laravel-4
大家在任何地方卡住,最快捷的解决方式就是去看我的示例代码。
推荐 Laravel 4.2 中文文档 http://laravel-china.org/docs
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 的配置文件” 方式配置。
镜像配置完成后,切换到你想要放置该网站的目录下,运行命令:
composer create-project laravel/laravel learnlaravel 4.2.11
为了大家学习的方便,请暂时使用 4.2.11 版本进行入门。春节假期我会抽时间写一下 Laravel 5 的入门教程。4.2.11 的 Github 下载地址为:https://github.com/laravel/laravel/archive/v4.2.11.zip
然后,稍等片刻,当前目录下就会出现一个叫 learnlaravel 的文件夹,这时候如果你通过浏览器访问 learnlaravel/public/ 目录,基本都会显示 Error in exception handler. ,这是因为 learnlaravel/app/storage 目录没有 777 权限,设置好权限即可看见页面如下图:
恭喜你~Laravel安装成功!
不想配置镜像的同学,可以使用 Laravel 界非常著名的超超搞得安装神器:https://github.com/overtrue/latest-laravel
2. 必要插件安装及配置
我们使用著名的Sentry插件来构建登录等权限验证系统。
打开 ./composer.json ,变更为:
"require": { "laravel/framework": "4.2.*", "cartalyst/sentry": "2.1.4" },
然后,在项目根目录下运行命令
composer update
然后稍等一会儿,它会提示 cartalyst/sentry 2.1.4安装完成。
同理,我们将安装一个开发用的非常强大的插件,way/generators,这是它在composer库中的名字。在 composer.json中增加:
"require-dev": { "way/generators": "~2.0" },
和“require”同级,放在下面,不是里面哦~。
运行 composer update,之后在 ./app/config/app.php 中 恰当的位置 增加配置:
'Way\Generators\GeneratorsServiceProvider'
安装完成过,在命令行中运行 php artisan,就可以看到这个插件带来的许多新的功能。
有人会问,为什么用了国内镜像还是如此之慢?其实composer在update的时候最慢的地方并不是下载,而是下载之前的依赖关系解析,由于Laravel依赖的composer包非常之多,PHP脚本的执行速度又比较慢,所以每次update等个两三分钟很正常,习惯就好。
3. 数据库建立及迁移
数据库配置文件位于 ./app/config/database.php,我们需要把“connections”中的“mysql”项改成我们需要的配置。下面是我的配置:
'mysql' => array( 'driver' => 'mysql', 'host' => 'localhost', 'database' => 'laravel', 'username' => 'root', 'password' => 'password', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => 'l4_', ),
prefix为表前缀,这个Laravel会帮我们自动维护,大胆写上不用担心。
这时候你需要去数据库建立此数据库,然后在命令行中输入:
php artisan migrate --package=cartalyst/sentry
执行完成后,你的数据库里就有了5张表,这是sentry自己建立的。sentry在Laravel4下的配置详情见 https://cartalyst.com/manual/sentry#laravel-4,我大致说一下:
在 ./app/config/app.php 中 相应的位置 分别增加以下两行:
'Cartalyst\Sentry\SentryServiceProvider',
'Sentry' => 'Cartalyst\Sentry\Facades\Laravel\Sentry',
权限系统的数据库配置到此为止。
我们的简单blog系统将会有两种元素,Article和Page,下面我们将创建articles和pages数据表,命令行运行:
php artisan migrate:make create_articles_table --create=articles php artisan migrate:make create_pages_table --create=pages
这时候,去到 ./app/database/migrations,将会看到多出了两个文件,这就是数据库迁移文件,过一会我们将操作artisan将这两个文件描述的两张表变成数据库中真实的两张表,放心,一切都是自动的。
下面,在***_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表就建立完成了。
4. 模型 Models
接下来我们将接触Laravel最为强大的部分,Eloquent ORM,真正提高生产力的地方,借用库克的话说一句,鹅妹子英!
我们在命令行运行下列语句以创建两个model:
php artisan generate:model article php artisan generate:model page
这时候,在 app/models/ 下就出现了两个文件 Article.php 和 Page.php,这是两个 Model 类,他们都继承了Laravel提供的核心类 \Eloquent。这里需要强调一下,用命令行的方式创建文件,和自己手动创建文件没有任何区别,你也可以尝试自己创建这两个 Model 类哦。
Model 即为 MVC 中的 M,翻译为 模型,负责跟数据库交互。在 Eloquent 中,数据库中每一张表对应着一个 Model 类。
如果你从其他框架转过来,可能对这里一笔带过的 Model 部分很不适应,没办法,是因为 Eloquent 实在太强大了啦,真的没什么好做的,继承一下 Eloquent 类就能实现很多很多功能了。详见 Eloquent 系列教程:深入理解 Laravel Eloquent(一)——基本概念及用法
5. 数据库填充
分别运行下列命令:
php artisan generate:seed page php artisan generate:seed article
这时,在 ./app/database/seeds/ 下就出现了两个新的文件,这就是我们的数据库填充文件。Laravel提供自动数据库填充,十分方便。
generator默认使用Faker\Factory作为随机数据生成器,所以我们需要安装这个composer包,地址是 https://packagist.org/packages/fzaninotto/faker ,跟generator一起安装在 require-dev 中即可。具体安装请自行完成,可以参考Sentry和Generator,这是第一次练习。
接下来,分别更改这两个文件:
Article::create([ 'title' => $faker->sentence($nbWords = 6), 'slug' => 'first-post', 'body' => $faker->paragraph($nbSentences = 5), 'user_id' => 1, ]);
Page::create([ 'title' => $faker->sentence($nbWords = 6), 'slug' => 'first-page', 'body' => $faker->paragraph($nbSentences = 5), 'user_id' => 1, ]);
然后,我们需要在 DatabaseSeeder.php 中增加两行,让Laravel在seed的时候会带上我们新增的这两个seed文件。
$this->call('ArticleTableSeeder'); $this->call('PageTableSeeder');
下面就要真正的把数据填充进数据库了:
php artisan db:seed
操作完成以后去数据库看看,数据已经填充进去了,article和page各10行。
接下来做什么?Laravel 4 系列入门教程(二)
评论:
2015-01-29 12:53
因为,安装完之后,
php artisan
可以看到
key
key:generate Set the application key
2015-01-29 13:19
在 composer.json 中添加
"require-dev": {
"way/generators": "~2.0"
},
然后,命令行
E:\wamp\www\laravel>composer update
Loading composer repositories with package information
Updating dependecies (including require-dev)
- installing way/generators (2.6.1)
Downloading:connection ... Downloading: 0%
Downloading:20%
Downloading:35%
Downloading:40%
Downloading:55%
Downloading:75%
Downloading:95%
Downloading:100%
Writing lock file
Generating autoload files
Generating optimized class loader
Compiling common classes
Compiling views
E:\wamp\www\laravel>
然后,在 app.php 中
'Way\Generators\GeneratorsServiceProvider',
然后在回到 命令行 ,创建模型,
就提示 我给您第一次发的 错误消息。
2015-01-29 14:17
2015-01-06 19:25
( ! ) Parse error: syntax error, unexpected '[' in G:\wamp\www\laravel\vendor\laravel\framework\src\Illuminate\Support\helpers.php on line 426
Call Stack
# Time Memory Function Location
1 0.0005 366768 {main}( ) ..\server.php:0
2 0.0014 370376 require_once( 'G:\wamp\www\laravel\public\index.php' ) ..\server.php:19
3 0.0017 376744 require( 'G:\wamp\www\laravel\bootstrap\autoload.php' ) ..\index.php:21
4 0.0019 378584 require( 'G:\wamp\www\laravel\vendor\autoload.php' ) ..\autoload.php:17
5 0.0024 398840 ComposerAutoloaderInit65218a41523806b5ded47d41b70cea77::getLoader( ) ..\autoload.php:7
6 0.0140 1067000 composerRequire65218a41523806b5ded47d41b70cea77( ) ..\autoload_real.php:49
426行的代码:
function class_uses_recursive($class)
{
$results = []; /*(这个是第426行)*/
foreach (array_merge([$class => $class], class_parents($class)) as $class)
{
$results += trait_uses_recursive($class);
}
return array_unique($results);
}
2015-01-05 12:41
如这样的关联关系User->Information,是一对一的关系。user的model与information的model都有hasOne()。可是当我使用$user->information->description时会报这样的错Trying to get property of non-object。而使用Eloquent的话,$information = User::find($id)->information;是没问题的。我这样的推断是对吗?
2015-01-05 02:15
<pre>
"require-dev": {
"way/generators": "2.*"
},
并且app.php中也添加了
'Way\Generators\GeneratorsServiceProvider',
composer update --dev也更新成功了,可是执行
Laravel Framework version 4.2.16
Usage:
[options] command [arguments]
Options:
--help -h Display this help message.
--quiet -q Do not output any message.
--verbose -v|vv|vvv Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug.
--version -V Display this application version.
--ansi Force ANSI output.
--no-ansi Disable ANSI output.
--no-interaction -n Do not ask any interactive question.
--env The environment the command should run under.
Available commands:
changes Display the framework change list
clear-compiled Remove the compiled class file
down Put the application into maintenance mode
dump-autoload Regenerate framework autoload files
env Display the current framework environment
help Displays help for a command
list Lists commands
migrate Run the database migrations
optimize Optimize the framework for better performance
routes List all registered routes
serve Serve the application on the PHP development server
tail Tail a log file on a remote server
tinker Interact with your application
up Bring the application out of maintenance mode
workbench Create a new package workbench
asset
asset:publish Publish a package's assets to the public directory
auth
auth:clear-reminders Flush expired reminders.
auth:reminders-controller Create a stub password reminder controller
auth:reminders-table Create a migration for the password reminders table
cache
cache:clear Flush the application cache
cache:table Create a migration for the cache database table
command
command:make Create a new Artisan command
config
config:publish Publish a package's configuration to the application
controller
controller:make Create a new resourceful controller
db
db:seed Seed the database with records
key
key:generate Set the application key
migrate
migrate:install Create the migration repository
migrate:make Create a new migration file
migrate:publish Publish a package's migrations to the application
migrate:refresh Reset and re-run all migrations
migrate:reset Rollback all database migrations
migrate:rollback Rollback the last database migration
queue
queue:failed List all of the failed queue jobs
queue:failed-table Create a migration for the failed queue jobs database table
queue:flush Flush all of the failed queue jobs
queue:forget Delete a failed queue job
queue:listen Listen to a given queue
queue:restart Restart queue worker daemons after their current job.
queue:retry Retry a failed queue job
queue:subscribe Subscribe a URL to an Iron.io push queue
queue:work Process the next job on a queue
session
session:table Create a migration for the session database table
view
view:publish Publish a package's views to the application
</pre>
这里没有generate:model? 求帮助。
2014-12-29 11:56
<pre>
"require-dev": {
"way/generators": "2.*"
},
并且app.php中也添加了
'Way\Generators\GeneratorsServiceProvider',
composer update --dev也更新成功了,可是执行
Laravel Framework version 4.2.16
Usage:
[options] command [arguments]
Options:
--help -h Display this help message.
--quiet -q Do not output any message.
--verbose -v|vv|vvv Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug.
--version -V Display this application version.
--ansi Force ANSI output.
--no-ansi Disable ANSI output.
--no-interaction -n Do not ask any interactive question.
--env The environment the command should run under.
Available commands:
changes Display the framework change list
clear-compiled Remove the compiled class file
down Put the application into maintenance mode
dump-autoload Regenerate framework autoload files
env Display the current framework environment
help Displays help for a command
list Lists commands
migrate Run the database migrations
optimize Optimize the framework for better performance
routes List all registered routes
serve Serve the application on the PHP development server
tail Tail a log file on a remote server
tinker Interact with your application
up Bring the application out of maintenance mode
workbench Create a new package workbench
asset
asset:publish Publish a package's assets to the public directory
auth
auth:clear-reminders Flush expired reminders.
auth:reminders-controller Create a stub password reminder controller
auth:reminders-table Create a migration for the password reminders table
cache
cache:clear Flush the application cache
cache:table Create a migration for the cache database table
command
command:make Create a new Artisan command
config
config:publish Publish a package's configuration to the application
controller
controller:make Create a new resourceful controller
db
db:seed Seed the database with records
key
key:generate Set the application key
migrate
migrate:install Create the migration repository
migrate:make Create a new migration file
migrate:publish Publish a package's migrations to the application
migrate:refresh Reset and re-run all migrations
migrate:reset Rollback all database migrations
migrate:rollback Rollback the last database migration
queue
queue:failed List all of the failed queue jobs
queue:failed-table Create a migration for the failed queue jobs database table
queue:flush Flush all of the failed queue jobs
queue:forget Delete a failed queue job
queue:listen Listen to a given queue
queue:restart Restart queue worker daemons after their current job.
queue:retry Retry a failed queue job
queue:subscribe Subscribe a URL to an Iron.io push queue
queue:work Process the next job on a queue
session
session:table Create a migration for the session database table
view
view:publish Publish a package's views to the application
</pre>
这里没有generate:model? 求帮助。
2014-12-25 20:33
我自己创建的problem表,在seed填充时,它非得去找problems这张表。。。
有没有方法设置不自动寻找表名的复数形式。。
2014-12-24 20:36
php artisan db:seed
出现以下错误
PHP Fatal error: Class 'Article' not found in /Library/WebServer/Documents/work_com/composer/laravel/learnlaravel/app/database/seeds/ArticleTableSeeder.php on line 14
2014-12-25 13:01
Article::create([
'title' => $faker->sentence($nbWords = 6),
'slug' => 'first-post',
'body' => $faker->paragraph($nbSentences = 5),
'user_id' => 1,
]);
2014-12-18 08:22
2014-12-18 08:20
这个实质是在public function up() 里面插入,可以写得更明确些。
2014-12-09 08:37
Do you really wish to run this command?
PHP Fatal error: Class 'Faker\Factory' not found in E:\wamp\www\laravel-master\app\database\seeds\ArticleTableSeeder.php on line 10
PHP Stack trace:
PHP 1. {main}() E:\wamp\www\laravel-master\artisan:0
PHP 2. Symfony\Component\Console\Application->run() E:\wamp\www\laravel-master\artisan:59
PHP 3. Symfony\Component\Console\Application->doRun() E:\wamp\www\laravel-master\vendor\symfony\console\Symfony\Component\Console\Application.php:124
PHP 4. Symfony\Component\Console\Application->doRunCommand() E:\wamp\www\laravel-master\vendor\symfony\console\Symfony\Component\Console\Application.php:193
PHP 5. Illuminate\Console\Command->run() E:\wamp\www\laravel-master\vendor\symfony\console\Symfony\Component\Console\Application.php:889
PHP 6. Symfony\Component\Console\Command\Command->run() E:\wamp\www\laravel-master\vendor\laravel\framework\src\Illuminate\Console\Command.php:100
PHP 7. Illuminate\Console\Command->execute() E:\wamp\www\laravel-master\vendor\symfony\console\Symfony\Component\Console\Command\Command.php:252
PHP 8. Illuminate\Database\Console\SeedCommand->fire() E:\wamp\www\laravel-master\vendor\laravel\framework\src\Illuminate\Console\Command.php:112
PHP 9. DatabaseSeeder->run() E:\wamp\www\laravel-master\vendor\laravel\framework\src\Illuminate\Database\Console\SeedCommand.php:57
PHP 10. Illuminate\Database\Seeder->call() E:\wamp\www\laravel-master\app\database\seeds\DatabaseSeeder.php:15
PHP 11. ArticleTableSeeder->run() E:\wamp\www\laravel-master\vendor\laravel\framework\src\Illuminate\Database\Seeder.php:37
{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"Class 'Faker\\Factory' not found","file":"E:\\wamp\\www\\laravel-master\\app\\database\\seed
s\\ArticleTableSeeder.php","line":10}}
2014-12-03 19:09
"laravel/framework": "4.2.*",
"cartalyst/sentry": "2.1.4"
},然后执行composer update后,cartalyst/sentry suggests installing happydemon/txt (Required Text helpers when
using the Kohana implementation),啥意思。。
下面还有一些内容是
Writing lock file
Generating autoload files
Generating optimized class loader
Compiling common classes
Compiling views
万分感谢
2014-11-09 16:20
===================
打开 ./composer.json ,变更为:
"require": {
"laravel/framework": "4.2.*",
"cartalyst/sentry": "2.1.4"
},
然后,在项目根目录下运行命令
composer update
==================
报这个错误,查了相关资料,不知道什么意思,楼主能解答下吗?
Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 680855 bytes) in phar:///usr/local/Cellar/composer/1.0.0-alpha8/libexec/composer.phar/src/Composer/Repository/ComposerRepository.php on line 281
2015-01-29 11:18
提示:
[InvalidArgumentException]
There are no commands defined in the "generate" namespace.
这个错误!!!,怎么办?
老师 ,帮帮我 ,非常感谢,,,,