Laravel初步使用

Laravel初步使用

一、laravel的初步使用

  1. 切换到laravel目录下,创建登陆认证页面

php artisan make:auth

  1. 创建模型(模型对应数据库的一张表)

php artisan make:model Article

  1. 迁移(迁移是为了设计数据库的表结构)
  • 创建迁移

php artisan make:migration create_articles_table

  • 编辑迁移文件

/database/migrations/2*_create_articles_table的up函数为:

public function up()
{
    Schema::create('articles', function (Blueprint $table)
    {
        $table->increments('id');
        $table->string('title');
        $table->text('body')->nullable();
        $table->integer('user_id');
        $table->timestamps();
    });
}
  • 开始迁移

    php artisan migrate

    如报错,执行php artisan migrate:fresh命令即可

  1. 使用Seeder填充数据(填充假数据,用于测试)
  • 创建Seeder php artisan make:seeder ArticleSeeder
  • 编辑seeder 修改/database/seeds/ArticleSeeder.php中的run函数为:
public function run()
{
    DB::table('articles')->delete();

    for ($i=0; $i < 10; $i++) {
        \App\Article::create([
            'title'   => 'Title '.$i,
            'body'    => 'Body '.$i,
            'user_id' => 1,
        ]);
    }
}
  • 加载创建的Seeder文件

修改/database/seeds/DatabaseSeeder.php中的run函数为:

public function run()
{
    $this->call(ArticleSeeder::class);
}
  • 开始填充

    php artisan db:seed

    扫描二维码关注公众号,回复: 588556 查看本文章

猜你喜欢

转载自www.cnblogs.com/lzhd24/p/9028015.html