Laravel 构建Restful风格 API

1.创建模型

php artisan make:model Article -m

2.修改默认生成的数据迁移文件

类名为CreateArticlesTable

将默认的迁移文件修改为如下,就是数据库字段的一些定义啦

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateArticlesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('articles');
    }
}

3.根据模型反向生成数据库表

php artisan migrate

4.修改数据模型

编辑 Article 模型类添加如下属性到 $fillable 字段以便可以在 Article::create 和 Article::update方法中可以使用它们:

class Article extends Model
{
    protected $fillable = ['title', 'body'];
}

5.数据库填充数据

Laravel 通过 Faker 库可以快速为我们生成格式正确的测试数据:

php artisan make:seeder ArticlesTableSeeder

生成的填充器类位于 /database/seeds 目录下,我们编辑填充器类如下:

use Illuminate\Database\Seeder;
use App\Article;

class ArticlesTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // Let's truncate our existing records to start from scratch.
        Article::truncate();

        $faker = \Faker\Factory::create();

        // And now, let's create a few articles in our database:
        for ($i = 0; $i < 50; $i++) {
            Article::create([
                'title' => $faker->sentence,
                'body' => $faker->paragraph,
            ]);
        }
    }
}

然后运行填充命令:

php artisan db:seed --class=ArticlesTableSeeder

6.创建控制器

接下来我们来创建控制器及方法:

php artisan make:controller ArticleController --resource

然后编辑控制器如下:

7.配置路由

调整 routes/api.php 文件中的 articles 相关路由:

Route::get('articles', 'ArticleController@index');
Route::get('articles/{id}', 'ArticleController@show');
Route::post('articles', 'ArticleController@store');
Route::put('articles/{id}', 'ArticleController@update');
Route::delete('articles/{id}', 'ArticleController@delete');

猜你喜欢

转载自blog.csdn.net/a1513049385/article/details/88537198