Laravel 4 系列入门教程(一)【最适合中国人的Laravel教程】

2014-9-29   /   字数:5290   /   阅读数:192627   /   分类: 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 权限,设置好权限即可看见页面如下图:

QQ20140930-3.jpg

恭喜你~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 系列入门教程(二)

WRITTEN BY

avatar
标签: PHP Laravel

评论:

zhangkz
2016-03-25 10:37
php artisan migrate:make create_articles_table --create=articles
php artisan migrate:make create_pages_table --create=pages
这两句有错误,不应该是migrate:make,而是make:migrate
JohnLui
2016-03-25 10:42
@zhangkz:4 时代大家还是用的 way 的 generator 插件,这个功能是在 5 才集成到 artisan 里的。
相思人
2015-12-16 20:23
大哥,你的laravel教程 我看了,很不错,我有一个问题:
1,你用的symfony  调试不是默认的laravel调试吧,你怎么配置的呢?
码农一枚
2015-10-01 20:46
请问:搭建成功,但是每当提交注册的时候就会提示“Method [validator] does not exist.”  这是什么原因?
warnerwu
2017-02-10 18:22
@码农一枚:方法过滤不存在
小刘
2015-08-18 17:03
老师啊,出个用项目串讲的laravel5视频吧!!!
guoer
2015-06-17 13:56
第一次就被安装的步骤吓到了啊
秋风888
2015-06-11 18:32
看完第一章,非常有用。谢谢老师。

只是文中下面这段代码,是不是粘贴重复了,和数据表结构对应不上啊。
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,
]);
JohnLui
2015-06-11 21:02
@秋风888:可能吧,但是建议去学 5 哦~
php初学者~
2015-09-10 12:13
@JohnLui:在一家公司想套用该框架,可惜php版本不高,最多只能用版本4,应该也没什么问题吧
JohnLui
2015-09-10 13:03
@php初学者~:有问题,完全跑不起来的。。。
page
2015-05-16 13:49
666666,文章写的很好,赞
长青
2015-04-28 14:45
这个Faker\Factory或者fzaninotto/faker怎么安装?这个问题搞了我一个星期了,很急,很重要,我们就要用laravel做项目的

我是在github下载了 faker 的安装包解压到 vendor 目录下,然后又在 app\config\app.php 文件的 'providers' 数组中添加了 'Fzaninotto\Faker\FakerServiceProvider'。就是不行,一直报错“ymfony \ Component \ Debug \ Exception \ FatalErrorException (E_UNKNOWN)

Class 'Fzaninotto\Faker\FakerServiceProvider' not found ” ;求详细安装教程!
JohnLui
2015-04-28 15:21
@长青:Faker 可能需要老版本才支持 Laravel 4 了,推荐直接用 5。
cstabor
2015-04-20 23:23
Installing laravel/laravel (v4.2.11)
  - Installing laravel/laravel (v4.2.11)
    Downloading: 100%        
    Failed to download laravel/laravel from dist: RecursiveDirectoryIterator::__construct(learnlaravel/): failed to open dir: No such file or directory
    Now trying to download from source

安装总是提示这个错误。
JohnLui
2015-04-28 15:21
@cstabor:建议用 5 。
徒步远行
2015-04-10 18:16
Warning: require(/webserver/program/laravel/bootstrap/../vendor/autoload.php): failed to open stream: No such file or directory in /webserver/program/laravel/bootstrap/autoload.php on line 16

Fatal error: require(): Failed opening required '/webserver/program/laravel/bootstrap/../vendor/autoload.php' (include_path='.:/usr/share/php:/usr/share/pear') in /webserver/program/laravel/bootstrap/autoload.php on line 16

安装了没有vendor 目录
JohnLui
2015-04-10 18:43
@徒步远行:这是因为没有执行 composer dump-autoload 的原因
TIM
2015-03-27 14:24
laravel 5
执行了php artisan mak:console  FindUser
然后也写好了
<?php namespace Yoyo\Console\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class UserFind extends Command {
    protected $name = 'user:find';

    protected $description = 'user:find';

    public function __construct()
    {
        parent::__construct();
    }

    public function fire()
    {
        $this->line('hello world');
    }

    protected function getArguments()
    {
        return [
            //['example', InputArgument::REQUIRED, 'An example argument.'],
        ];
    }

    protected function getOptions()
    {
        return [
            //['example', null, InputOption::VALUE_OPTIONAL, 'An example option.', null],
        ];
    }

}

怎么将他添加到php artisan user:find来执行,
JohnLui
2015-03-27 15:24
@TIM: 没搞过
MoGoethe
2015-03-26 17:34
Administrator@USER-20150318JG /c/wamp/www/learnlaravel (master)
$ php artisan migrate --package=cartalyst/sentry
**************************************
*     Application In Production!     *
**************************************
Do you really wish to run this command? yes

  [PDOException]
  SQLSTATE[HY000] [2002] 目芫薹印


migrate [--bench[="..."]] [--database[="..."]] [--force] [--path[="..."]] [--pac
kage[="..."]] [--pretend] [--seed]
老师您好,如果wamp处于关闭状态只要执行 : $ php artisan migrate --package=cartalyst/sentry    这个命令就会出现上面这个问题,

如果  打开 wamp 那就会出现:
$ php artisan migrate --package=cartalyst/sentry
**************************************
*     Application In Production!     *
**************************************

Do you really wish to run this command? yes


  [PDOException]
  SQLSTATE[HY000] [1049] Base 'laravel' inconnue


migrate [--bench[="..."]] [--database[="..."]] [--force] [--path[="..."]] [--pac
kage[="..."]] [--pretend] [--seed]

这个问题,请问是怎么回事啊?我已经配置了N遍了
JohnLui
2015-03-26 17:49
@MoGoethe:去看 5 的教程吧。。。很多第三方包已经更新了,默认只支持 5 了。
Bpio
2015-03-02 23:12
老师,老师,给出个5.0的教程吧!5.0变化有些大啊!
artisan好多命令都变了!目录结构也变了!
zone
2015-03-02 08:16
老师,请教个问题,为什么为执行
composer create-project laravel/laravel blog 4.2.11
老是出现这个异常呢,
[Symfony\Component\Process\Exception\RuntimeException]  
  The process has been signaled with signal "11".

还有,laravel 5 有教程吗!!
baren
2015-02-25 03:37
D:\Apache2.2\htdocs\laravel>php artisan db:seed
PHP Fatal error:  Class 'Fzaninotto\Faker\FakerServiceprovider' n
Apache2.2\htdocs\laravel\bootstrap\compiled.php on line 4481
{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErro
ssage":"Class 'Fzaninotto\\Faker\\FakerServiceprovider' not found
pache2.2\\htdocs\\laravel\\bootstrap\\compiled.php","line":4481}}
D:\Apache2.2\htdocs\laravel>

老师:如上所示错误该怎么处理,拜谢
baren
2015-02-26 19:16
@baren:明明安装了Faker却还是不行
果大王
2015-02-14 23:24
惭愧惭愧   望上个评论不要通过审核了  感谢你的教程  祝愿新年技术更上一层楼
wusp
2015-02-11 10:42
老师你好,在使用您推荐的composer全量中国镜像的composer.json文件,并执行install之后,我碰到了这个问题:

wuspdeMacBook-Air:laravel-master wusp$ composer install
Loading composer repositories with package information
Installing dependencies (including require-dev)
                                                                            
  [Composer\Downloader\TransportException]                                    
  The "http://pkg.phpcomposer.com/repo/packagist/p/illuminate/pagination.json  
  " file could not be downloaded: php_network_getaddresses: getaddrinfo faile  
  d: nodename nor servname provided, or not known                              
  failed to open stream: php_network_getaddresses: getaddrinfo failed: nodena  
  me nor servname provided, or not known

同时在命令行使用 php artisan serve命令时出现以下反馈:
wuspdeMacBook-Air:laravel-master wusp$ php artisan

Warning: require(/Applications/Web/laravel-master/bootstrap/../vendor/autoload.php): failed to open stream: No such file or directory in /Applications/Web/laravel-master/bootstrap/autoload.php on line 17

Fatal error: require(): Failed opening required '/Applications/Web/laravel-master/bootstrap/../vendor/autoload.php' (include_path='.:') in /Applications/Web/laravel-master/bootstrap/autoload.php on line 17

请问这个问题是如何引发的,该如何解决呢?
谢谢!
JohnLui
2015-02-11 12:55
@wusp:中国镜像会暂时抽疯。稳妥的解决办法是开 VPN 直连国外服务器。
后面一个问题是因为没有 composer update 安装依赖包导致的,在这个状态下,网站跑不起来。
ok
2015-02-10 15:15
Symfony \ Component \ HttpKernel \ Exception \ NotFoundHttpException 这是为啥·?
JohnLui
2015-02-10 15:38
@ok:路由匹配失败,404 的意思。
沐风待雨
2015-02-10 10:36
Generating autoload files
exception "BadMethodCallException" with message "Call to undefined method [package]" in D:\wamp\www\laravel\storage\framework\compiled.php 4346

在composer update 或者 php artisan 后会提示这个错误。我用的是laravel 5
composer.json 文件如下
{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "laravel/framework": "5.0.*",
        "cartalyst/sentry": "2.1.4"
    },
    "require-dev": {
        "way/generators": "~3.0",
        "phpunit/phpunit": "~4.0",
        "phpspec/phpspec": "~2.1"
    },
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "classmap": [
            "tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-install-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-update-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-create-project-cmd": [
            "php -r \"copy('.env.example', '.env');\"",
            "php artisan key:generate"
        ]
    },
    "config": {
        "preferred-install": "dist"
    }
}
JohnLui
2015-02-10 11:41
@沐风待雨:sentry 2 不支持 Laravel 5。
沐风待雨
2015-02-10 21:59
@JohnLui:那怎么整呢,"cartalyst/sentry": "2.1.4" ,你sh4o的sentry 2 是指的这个吗?那这里应该用sentry 那个版本?
JohnLui
2015-02-11 12:56
@沐风待雨:Sentry 3 是收费的
沐风待雨
2015-02-23 01:32
@JohnLui:。。。。汗
penkku
2015-01-29 16:07
成功! 见到了楼主所说的丑页面。谢谢楼主!

总结一下,从安装到现在,遇到了几处难点:

1,安装第一步,“切换到你想要放置该网站的目录下”
一开始不知道网站根目录指的是哪里,还以为是public目录,百度上问也没人回答,google外国网站,才得知是app的父目录,这个难点差点把我挡在laravel门外。如果教程中写明网站的目录就是app的父目录就好了。

2,"require": {
    "laravel/framework": "4.2.*",
    "cartalyst/sentry": "2.1.4"
},
4.2.*原封不动就这样写。不要写成4.2.11之类的。

3,composer.json就在learnlaravel根目录下。我一开始用的是/learnlaravel/vendor/laravel/framework/src/Illuminate/Support/composer.json,导致安装Sentry等插件失败。

4,View [admin._partials.assets] not found.
不知道admin._partials.assets放在哪个目录下,看评论才知是在\app\views\admin\_partials目录下添加assets.blade.php这个文件,刷新后提示找不到admin._partials.navigation,如法炮制一下就好了。
骆oo海
2015-01-29 11:18
您好,老师,当我在命令行  php artisan generate:model page  创建模型时,

提示:
[InvalidArgumentException]
There are no commands defined in the "generate" namespace.

这个错误!!!,怎么办?
老师 ,帮帮我 ,非常感谢,,,,
JohnLui
2015-01-29 12:25
@骆oo海:way/generators 包没有安装成功。
骆oo海
2015-01-29 12:53
@JohnLui:老师,我觉得 应该是安装成功了吧,按照您给的步骤一步步走的,
因为,安装完之后,
php artisan
可以看到
key
key:generate                Set the application key
骆oo海
2015-01-29 13:19
@JohnLui:老师,我是这样做的
在 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',

然后在回到 命令行 ,创建模型,
就提示  我给您第一次发的 错误消息。
JohnLui
2015-01-29 14:17
@骆oo海:应该是 Way\Generators\GeneratorsServiceProvider 这一句没有放在正确的位置上。你参考我给的那个链接的文件吧。
骆oo海
2015-01-29 14:38
@JohnLui:嗯嗯,老师是我自己放错位置了,感谢老师给我解答,总之,一句话 ,万分感谢!
tsh
2015-07-23 11:03
@骆oo海:要放在什么位置啊 我也出现这个错误了
骆oo海
2015-02-03 12:13
@JohnLui:老师能给我说一下:laravel 中 Redirect::to  和 Redirect::route 的区别吗?
骆oo海
2015-02-03 16:05
@骆oo海:还有老师,您要是 能给这个案例做个  单元测试 ,那就更完美了。
现在我已经,把您给的这个案例了解了百分之五六十了,对于我这个初学者来说,这个入门案例,真的非常棒,很有用,还有就是,很感谢老师。希望老师能采纳我的建议,给我们这样的初学者一个很好的开头,我们会感激您的。
xdd
2015-01-06 19:25
你好,老师。我在搭建laravel过程中,搭建完成后,输入主机 出现下面的错误,请问怎么解决 谢谢老师


( ! ) 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);
    }
JohnLui
2015-01-06 20:51
@xdd:这是因为 PHP 版本不够
Laravel 需要 PHP5.4 以上,在 5.4.0 版本才有用中括号 [ ] 定义数组的功能。
xdd
2015-01-07 19:25
@JohnLui:谢谢指教,昨晚发现了这个问题就重新搭了个环境,现在正在学习,谢谢
Salon.sai
2015-01-05 12:41
其实使用了Sentry的话 查询关联的时候是不是不能关联到其他的表呢?
如这样的关联关系User->Information,是一对一的关系。user的model与information的model都有hasOne()。可是当我使用$user->information->description时会报这样的错Trying to get property of non-object。而使用Eloquent的话,$information = User::find($id)->information;是没问题的。我这样的推断是对吗?
JohnLui
2015-01-05 12:53
@Salon.sai:可以关联。Sentry 只是一个插件,不会影响 Eloquent 原本的功能。调用模型间关系需要在查询的时候就查出来。是这样的:$users = User::find($id)->hasOne()->first(); 这样就可以查到一个复杂对象了。

具体的表间关系的操作我接下来会详细地在系列文章中讲述:http://lvwenhan.com/laravel/421.html
Salon.sai
2015-01-05 15:41
@JohnLui:好的 谢谢解答~
abc
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? 求帮助。
JohnLui
2015-01-05 12:54
@abc:
你对比一下在 app.php 和 composer.json 中你的代码和我的代码有什么区别,应该是位置不对造成的。
M2
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? 求帮助。
JohnLui
2014-12-29 14:02
@M2:史上最长回复诞生了

应该是 app.php 增加的位置不对~
M2
2014-12-29 14:07
@JohnLui:
发完贴 发现评论说要加在providers下,测试成功了。。
神之一一
2014-12-25 20:33
数据库表只能是复数吗。。。
我自己创建的problem表,在seed填充时,它非得去找problems这张表。。。
有没有方法设置不自动寻找表名的复数形式。。
JohnLui
2014-12-25 20:43
@神之一一:可以在 Model 中指定:protected $table = 'problem';
神之一一
2014-12-25 20:51
@JohnLui:嗯嗯,从另一篇关于Eloquent的文章中找到啦~谢谢~
levi
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
JohnLui
2014-12-25 09:11
@levi:Article 这个 model 不存在
levi
2014-12-25 13:01
@JohnLui:不对丫,你的教程里不就写的有这个模块嘛

Article::create([
  'title'   => $faker->sentence($nbWords = 6),
  'slug'    => 'first-post',
  'body'    => $faker->paragraph($nbSentences = 5),
  'user_id' => 1,
]);
JohnLui
2014-12-25 13:18
@levi:Model,翻译成模型,不是模块
这个错误说明你的 Article 这个 Model 没有建立成功~
levi
2014-12-25 18:43
@JohnLui:谢谢,搞定了
Twwy
2014-12-18 08:22
我错了。。根据 Schema::create('articles', function(Blueprint $table) 这行就可以找到,请无视我上一条留言。
Twwy
2014-12-18 08:20
| 下面,在***_create_articles_table.php中修改:

这个实质是在public function up() 里面插入,可以写得更明确些。
Twwy
2014-12-11 23:40
放在“require”的下面, 这个句子有些歧义,我还以为在require的大括号里面。建议可以写成和 require 同级会更准确一些
JohnLui
2014-12-12 11:05
@Twwy:谢谢建议~
ttlovephp
2014-12-09 08:37
为什么我按照教程第一讲步骤做的,最后在db:seed时,数据库一条数据都没有,cmd命令行好像出现了报错
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}}
JohnLui
2014-12-09 17:48
@ttlovephp:这是因为没有安装 Faker 包,我说了“请自行完成”,这也是一个小任务哦~
ttlovephp
2014-12-10 15:52
@JohnLui:谢谢你哟!真的是我少了这步操作的原因啊,继续学习,谢谢分享哈
沐风待雨
2015-02-23 14:16
@JohnLui:怎么安装Faker包啊。。
renjie
2014-12-03 19:09
"require": {
    "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
万分感谢
JohnLui
2014-12-04 08:58
@renjie:这都是正常的,放心吧~
renjie
2014-12-04 11:23
@JohnLui:真的非常感谢!
xiaobai
2014-11-27 16:43
对于我们这些不懂的人来说很实用,博主的功底很深啊
qsq
2014-11-27 11:42
不错不错~
ycoder
2014-11-19 16:40
中文的最好了,英语很差,谢谢
ycoder
2014-11-19 16:40
你好,sentry 有文档教程之类的吗?没找到,麻烦给个链接
kino
2014-11-13 15:55
从输入 php artisan migrate --package=cartalyst/sentry 开始

mysql数据库就是同步不过去啊啊啊啊
我赌五毛
2014-11-10 16:57
Faker 好像支持中文,请问那该怎么配置呢?
JohnLui
2014-11-10 23:06
@我赌五毛:不知道。。。
Ruchee
2014-12-24 14:14
@我赌五毛:use Faker\Factory as Faker;

$faker = Faker::create('zh_CN');

Page::create([
                'title'   => $faker->city(),
                'slug'    => 'first-page',
                'body'    => $faker->city(),
                'user_id' => 1,
]);

具体可以调用哪些方法,可自行查看 vendor\fzaninotto\faker\src\Faker\Provider\zh_CN 下的各个文件源码
tmdphp
2014-11-10 16:34
Jark
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
JohnLui
2014-11-10 22:56
@Jark:PHP 单进程内存超标,进程被杀掉。
Harlan
2014-11-08 01:05
感谢你的文章!
我在生成数据的时候遇到了这样的错误
PHP Fatal error:  Call to undefined method Faker\Factory::isDeferred() in /wwwroot/laravel/vendor/laravel/framework/src/Illuminate/Foundation/ProviderRepository.php on line 126

最后原因是:我在app.app加了Faker\Factory这样一个命名空间
fakecoder
2014-11-02 14:51
使用php artisan出现error:'Way\Generators\GeneratorsServiceProvider' not found。谷歌了一下,将'Way\Generators\GeneratorsServiceProvider'从app.php删除后反而好用了,我虚了,我这是病吗?
JohnLui
2014-11-02 21:35
@fakecoder:可能是放错地方了。。。
fakecoder
2014-11-03 10:04
@JohnLui:是放在provider数组里了啊,,而且后面配置sentry也是同样的问题。。昨天我又出现新问题了,用sentry就生成了一张表,不是五张,后来的article和page倒是能够生成了,这有影响吗?我感觉自己有些凌乱了
JohnLui
2014-11-03 11:12
@fakecoder:删掉local文件夹,只使用外的配置文件试试。注意看 composer.json 中的包版本。
fakecoder
2014-11-03 23:46
@JohnLui:你好,晚上才有时间弄,我把原来的工程删了,从头开始做,在安装sentry和generrator的时候提示:could not scan for classes inside app/commands which does not appear to be a file nor a folder。
我没管,然后删掉了local文件夹并在app.php中providers添加了'Way\Generators\GeneratorsServiceProvider',执行php artisan还是错误,删掉就好用。composer.json里的sentry版本都是从教程中复制过来的(composer.json是建工程之前我自己建的,貌似没问题吧)
有点小伤感
JohnLui
2014-11-04 10:23
@fakecoder:可能是你多执行了某一步操作,已经将generator注册到系统里了。多执行 composer update 。。。
fakecoder
2014-11-04 12:29
@JohnLui:貌似是,,那我继续往下做?影响大吗
JohnLui
2014-11-04 14:11
@fakecoder:建议重做。。。
fakecoder
2014-11-04 14:24
@JohnLui:重做是composer也要重装吗,还是只是重做工程?
JohnLui
2014-11-04 14:26
@fakecoder:重做工程。Composer 本质上就是一段 PHP 脚本,是不会变的。
fakecoder
2014-11-04 14:34
@JohnLui:好。我试试!谢了!
fakecoder
2014-11-04 22:27
@JohnLui:历经好几天,可算完成了第一个教程,都是自己的问题。。估计很少有人犯,说一下吧。我的毛病出在第一步,看composer配置的时候想当然的在laravel文件夹下直接建了一个composer.json文件,结果生成learnlaravel的时候里面会自带这个文件的,我改的一直是我自己建的文件,生成的没改,应该是问题所在吧。好吧,我2了谢谢
ilvsx
2014-11-01 00:21
对了,由于 Laravel 的 you have arrived 页面的 css 会加载 google font ,造成每次打开都要等上至少一分钟。
解决方法是,先下载Lato字体,然后找到 learnlaravel\app\views 目录下的 hello.php 文件修改:
- /*@import url(//fonts.googleapis.com/css?family=Lato:700);*/
+ /* latin-ext */
@font-face {
  font-family: 'Lato';
  font-style: normal;
  font-weight: 700;
  src: local('Lato Bold'), local('Lato-Bold'), url(http://fonts.gstatic.com/s/lato/v11/ObQr5XYcoH0WBoUxiaYK3_Y6323mHUZFJMgTvxaG2iE.woff2) format('woff2');
  unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
  font-family: 'Lato';
  font-style: normal;
  font-weight: 700;
  src: local('Lato Bold'), local('Lato-Bold'), url(http://fonts.gstatic.com/s/lato/v11/HdGTqbEHKKIUjL97iqGpTvY6323mHUZFJMgTvxaG2iE.woff2) format('woff2');
  unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}

或者修改成其他字体。
既然是新手教程,这里也可以提一下。
JohnLui
2014-11-01 02:54
@ilvsx:这个页面没什么价值…会被直接弃用…感谢你的反馈。
wilson
2014-10-30 16:50
写得不错,清晰易懂。
ilvsx
2014-10-29 18:07
- 运行 composer update,之后在 ./app/config/app.config 中增加配置:
+  运行 composer update,之后在 ./app/config/app.config 中 'providers' => array 增加配置:

纯新手又不懂英文这步就跳不过去了。。。
Once this operation completes, the final step is to add the service provider. Open app/config/app.php, and add a new item to the providers array.
JohnLui
2014-10-29 18:23
@ilvsx:不明白你想表达什么。。。你可以去参考我在 Github 上的代码。
ilvsx
2014-10-29 21:34
@JohnLui:./app/config/app.php 中增加配置

鬼知道这个增加配置是怎么增加的啊?
你这是入门+教程,这样写算是入门+教程?
要不是去看https://github.com/JeffreyWay/Laravel-4-Generators 的安装步骤写清楚了"add a new item to the providers array.",真的新手入门冲着这个适合中国人的标题来看,能明白这一步的配置往哪增加?

还说向http://www.codeforest.net/laravel4-simple-website-with-backend-1 致敬,看看人家怎么写的:EDIT: Some people complained there’s not enough info on installing Sentry, so basicaly you need to add the service provider and the alias to your app/config/app.php file:

如果你的标题不是 入门+教程+最适合中国人,我不会说什么。
JohnLui
2014-10-29 22:41
@ilvsx:"入门教程" 并不是 “一步一步跟我做”,我在教程的某些地方刻意留下一些大大小小的任务,就是要让学习的人自己去尝试着解决问题,在解决问题的过程中感受 Laravel 做事的逻辑。很多人确实会卡在这一步,评论里面已经有几个人的反馈了。其实我想写清楚也很容易,大不了贴个我在 Github 上相应文件的链接,但是我不想这样干,想让大家在卡住之后自己仔细看下这个文件中的代码,或者想到去看我的代码,学习自己解决问题的能力。要不我的教程是没有价值的,一步一步跟我做完之后还是不会自己往下做,遇到问题了也不会自己解决。还是要感谢你的回复,也会给后来者以帮助。
ilvsx
2014-10-29 23:33
@JohnLui:这里对于新手来说属于一个新知识点,应该先讲清楚,后面遇到类似知识点再设置提问。

抱歉,前面我语气很冲,希望您能谅解。
okokok
2014-12-14 19:00
@JohnLui:我觉得你做的对。那些问题我都一个一个找着解决了。感觉这做法挺好。我喜欢解决问题的过程。有几个问题还是到github上的找创始人的文档看的。composer dump-autoload 的,有一个没更新。我是composer update才解决的。
JohnLui
2014-10-29 23:37
@ilvsx:
很菜
2014-10-24 22:37
php artisan generate:model article
php artisan generate:model page
php artisan generate:seed page
php artisan generate:seed article
运行错误,显示:
  [InvalidArgumentException]
  There are no commands defined in the "generate" namespace.
已经在composer.json中配置,如下
"require-dev": {
        "way/generators": "~2.0",
        "fzaninotto/faker": "1.5.*@dev"
    },
没有在app.php中写配置,不知道要不要,新手不是很懂。
John·Lui
2014-10-24 23:16
@很菜:要。
Yorian
2014-10-31 15:25
@John·Lui:已经在composer.json中配置,如下
"require-dev": {
        "way/generators": "~2.0",
        "fzaninotto/faker": "1.5.*@dev"
    },
没有在app.php中写配置,不知道要不要,新手不是很懂。

您@很菜:要。说的是在app.php中配置以下内容吗?
"require-dev": {
        "way/generators": "~2.0",
        "fzaninotto/faker": "1.5.*@dev"
    },
不解??
JohnLui
2014-10-31 15:47
@Yorian:按照下面一行说的做就行了:"运行 composer update,之后在 ./app/config/app.php 中增加配置:"
Yorian
2014-10-31 15:46
@John·Lui:应该是将'Way\Generators\GeneratorsServiceProvider'加入到到providers数组中,希望作者修正下,以免新手造成误导!
JohnLui
2014-10-31 15:59
@Yorian:加上我的配置文件的链接了,这个地方不好描述。看来确实对很多人造成了困扰
Yorian
2014-10-31 17:10
@JohnLui:嗯,是的.后来看到你的文件链接了谢谢!
Frewen
2014-10-22 16:05
最后一步 php artisan db:seed 的时候出错。
[PDOException]
SQLSTATE[HY000]: General error: 1364 Field 'image' doesn't have a default v
alue

原因分析是:
在***_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();
});

中    $table->string('image')->nullable(); 设置成了必填项导致。

解决方案我认为有两种:
1:    $table->string('image')->nullable(); 修改成——>    $table->string('image');
2:数据数组中列添加相应值
Article::create([
  'title'   => $faker->sentence($nbWords = 6),
  'slug'    => 'first-post',
  'body'    => $faker->paragraph($nbSentences = 5),
  'image'  =>'xxxxxxxxxxxxxxxxxxxxxxxx',
  'user_id' => 1,
]);
John·Lui
2014-10-22 16:19
@Frewen:->nullable() 的意思是 “非必须”。
初学者
2014-10-12 10:15
运行 composer update,之后在 ./app/config/app.config 中增加配置:

1
    
'Way\Generators\GeneratorsServiceProvider'


我始终找不到“app.config”这个文件
John·Lui
2014-10-12 13:03
@初学者:./app/config/app.php 手误。
初学者
2014-10-12 21:49
@初学者:多谢!
Laravel 4 系列入门教程(一)已经试着做完,很有帮助。
金龙
2014-10-07 22:14
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'title' in 'field list'
我的mysql中列表没有更新,请问是少了什么步骤吗?
John·Lui
2014-10-07 23:06
@金龙:自己按照教程来,一步都不能少。这个出错信息太少了,没法分析。错误的意思大概是数据库没有 migrate 成功表结构,就用 seed 往里面填充数据了。
helloqidi
2014-10-24 10:20
@金龙:遇到同样的问题,原因是 在 app/config/local下也有一个database.php,需要修改此处的数据库连接。
具体请查看官方文档:http://laravel.com/docs/4.2/configuration#environment-configuration
John·Lui
2014-10-24 12:37
@helloqidi:默认总是 production 环境,不经过配置是不会启用 local 文件夹的。
金龙
2014-10-07 21:06
请问在Autoloaded Service Providers怎么配置faker。填写的ServiceProvider是哪个
John·Lui
2014-10-07 23:05
@金龙:不用填写,faker是普通 Composer 包,不是Laravel插件,是直接用命名空间载入使用的。
Julian
2014-10-07 15:24
Faker\Factory的安装,配置文件貌似不是在require-dev里,而是require里,官方说明里有,不知道应该是到底选哪个,好像如果是dev的必须也要对应dev版,如果是fzaninotto选择1.4.0,还是放在require里。
John·Lui
2014-10-07 15:46
@Julian:require-dev 和软件版本没有任何关系,你理解有误。
require-dev 是 Composer 的配置项,意思是开发用插件,线上部署的时候不用。默认的 composer update 是包含 dev 的,所以其实现阶段象征意义大于现实意义。Laravel可能会在部署的时候根据环境变量选择自动加载包,以达到减小命名空间树的目的(猜测)。
Julian
2014-10-07 16:09
@John·Lui:配置的时候我选用的是1.4.0,最新版的是1.5.*@dev,我如果按照你的操作,放在require-dev里,update不成功,放在require里就可以了,如果只是区分开发跟部署的关系的话,不论他是否自动加载,感觉都应该会有区分,如果是在dev里配置能成的话,不知道我这里是哪里出了问题
John·Lui
2014-10-07 16:14
@Julian:不成功有什么提示?这个包没有任何对于Laravel的依赖,不能用好解释,安装不成功就很奇怪了。require 和 require-dev 只有 composer 设置里有区分,跟软件版本绝对没有任何关系。
Julian
2014-10-07 16:26
@John·Lui:反正挺奇怪的,估计是我哪里配置没弄对吧,慢慢研究中,谢谢你文章了,正好找教程找不到
newbie2005
2014-10-04 02:17
請問兩個文件的位置
*********************************
接下来,分别更改这两个文件:
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,
]);
John·Lui
2014-10-04 11:47
@newbie2005:看上文:
这时,在 ./app/database/seeds/ 下就出现了两个新的文件,这就是我们的数据库填充文件。Laravel提供自动数据库填充,十分方便。
新学者
2014-11-13 15:46
@John·Lui:我在填充的是后出现了问题,告诉我有一个类未调用,怎么办啊(PHP Fatal error:  Class 'Faker\Factory' not found in D:\web1\apache\htdocs\learn
laravel\app\database\seeds\ArticleTableSeeder.php on line 10
{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","me
ssage":"Class 'Faker\\Factory' not found","file":"D:\\web1\\apache\\htdocs\\lear
nlaravel\\app\\database\\seeds\\ArticleTableSeeder.php","line":10}}
Jacob
2014-11-14 12:40
@新学者:1.在composer.json中require-dev下粘贴下面的内容
"fzaninotto/faker": "1.5.*@dev"

2.更新包
终端运行composer update

发表评论:

© 2011-2024 岁寒  |  Powered by Emlog