laravel笔记

向视图中传递变量

使用with()方法

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

直接给view()传参数

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

使用compact

return view('articles.lists',compact('title','intro'));

使用Migration

php artisan make:migration create_articles_table --create='articles'

php artisan migrate:rollback

php artisan migrate

时间处理库Carbon

$article->published_at = CarbonCarbon::now();

.env中我们设置了APP_DEBUG=true

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

使用illuminate/html

 安装

1、composer require illuminate/html

2、提供Service Provider和指定Facade

Request表单验证

1、php artisan make:request StoreArticleRequest 这个命令生成的文件位于app/Http/Requests/

2、会有两个方法:authorize()和 rules() 。

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

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

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

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

使用Validation

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

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

setAttribute

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

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

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

public function setPasswordAttribute($passowrd)
{
    $this->attributes['password'] = Hash::make($passowrd);
    //仅仅是举例
}
这里将published_at字段作为Carbon对象来处理,注意在文件头部使用use CarbonCarbon;来引入Carbon。

Article.php添加一行代码使published_at作为Carbon对象来处理:

protected $dates = ['published_at'];

queryScope

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

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

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

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

关联表
 public function up()
    {
        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

 
原文地址:https://www.cnblogs.com/mitang/p/4832144.html