您的位置:首页 > 编程语言 > PHP开发

laravel笔记

2015-09-23 14:44 531 查看

向视图中传递变量

使用with()方法

returnview('articles.lists')->with('title',$title);

直接给view()传参数

returnview('articles.lists',['title'=>$title]);

使用compact

returnview('articles.lists',compact('title','intro'));

使用Migration

phpartisanmake:migrationcreate_articles_table--create='articles'

phpartisanmigrate:rollback

phpartisanmigrate

时间处理库Carbon

$article->published_at=Carbon\Carbon::now();

.env
中我们设置了
APP_DEBUG=true


404
页面,在
resources/views/errors/
文件夹下创建一个
404.blade.php


使用illuminate/html

安装

1、composerrequireilluminate/html

2、提供ServiceProvider和指定Facade

Request表单验证

1、phpartisanmake:requestStoreArticleRequest这个命令生成的文件位于
app/Http/Requests/


2、会有两个方法:authorize()
和[code]rules()。[/code]

authorize()
可以这样简单地理解:我们在处理这个表单请求(通常是一个post请求)的时候是否是需要进行身份验证,这种验证是指:比如A发表的评论,B能不能进行编辑。如果不能,则保留返回
false
,如果可以,则修改返回
true
。那么我们这里的逻辑是:既然是发表文章,在我们这个站点注册的用户(如果开放注册的话)都是可以发表文章的,所以我们首先修改
authorize()
方法,将其返回值改为:
returntrue;


然后对于
rules()
方法,我们需要在这里设置我们的验证规则,比如我们可以设置下面这个的验证规则:

3、将整个
StoreArticleRequest
类的实例以
$request
变量传入
store()
方法

如果你不想错误信息为英文,可以到
resources/lang/en/validation.php
修改,或者你直接创建一个新的语言文件包。

使用Validation

$validator=Validator::make($input,['title'=>'required|min:3','body'=>'required',]);

if($validator->fails()){}

[b]setAttribute[/b]

1、在
Article.php
中添加下面的方法:

publicfunctionsetPublishedAtAttribute($date)
{
$this->attributes['published_at']=Carbon::createFromFormat('Y-m-d',$date);
}

这里注意这个写法
set+字段名+Attribute
,还有的就是使用驼峰法。比如你要加密密码的时候可以这样:

publicfunctionsetPasswordAttribute($passowrd)
{
$this->attributes['password']=Hash::make($passowrd);
//仅仅是举例
}
这里将published_at
字段作为Carbon对象来处理,注意在文件头部使用[code]useCarbon\Carbon;来引入Carbon。
[/code]
Article.php
添加一行代码使
published_at
作为Carbon对象来处理:

protected$dates=['published_at'];


[b]queryScope

[/b][/code]
1、
$articles=Article::where('published_at','<=',Carbon::now())->latest()->get();
$articles=Article::latest()->published()->get();

2、在我们的
Article.php
中增加下面的方法:

publicfunctionscopePublished($query)
{
$query->where('published_at','<=',Carbon::now());
}

这里注意一下写法
scope+自定义的方法名字
,还有就是一如既往的驼峰法。

[b]关联表[/b]


publicfunctionup()
{
Schema::create('article_tag',function(Blueprint$table){
$table->increments('id');
$table->integer('article_id')->unsigned()->index();
$table->foreign('article_id')->references('id')->on('articles')->onDelete('cascade');
$table->integer('tag_id')->unsigned()->index();
$table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
$table->timestamps();
});
}


foreign():外键references():参照字段on():参照表onDelete():删除时的执行动作
这里
cascade
是跟着删除,比如删除了某篇文章,我们将article_tag中包含article_id一样的记录也删除


getAttribute


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: