PHP

Laravel Restful API屋ことはじめ

Laravel

転職先でAPI作りにはげむことになるのでおさらい。

@see

ここのAPIだけの演習メモです。

 

モデルの作成(通常)

$ php artisan make:model Models/Article -m

モデルの作成(docker-compose環境)

$ docker-compose exec php-fpm php artisan make:model Models/Article -m

私はdocker-compose環境なので、後者で綴ります。

 

databases/migrations/2019_09_16_104733_create_articles_table.php

    public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });
    }

 

-rオプションでResourcefulなアクションを自動で定義したコントローラを作成

$ docker-compose exec php-fpm php artisan make:controller Api/ArticlesController -r

 

app/Http/Controllers/Api/ArticlesController.php

<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Models\Article;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redirect;

class ArticlesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $articles = Article::all();
        return $articles;
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $article = new Article;
        $article->title = $request->title;
        $article->body  = $request->body;
        $article->save();
        return redirect('api/articles');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $article = Article::find($id);
        return $article;
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $article = Article::find($id);
        $article->title = $request->title;
        $article->body  = $request->body;
        $article->save();
        return Redirect("api/articles/" . $id);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $article = Article::find($id);
        $article->delete();
        return redirect('api/articles');
    }
}

 

routes/api.php

- Route::middleware('auth:api')->get('/user', function (Request $request) {
-     return $request->user();
- });
+ //Route::middleware('auth:api')->get('/user', function (Request $request) {
+ //    return $request->user();
+ //});

+ Route::group(['middleware' => ['api']], function(){
+     Route::resource('articles', 'Api\ArticlesController', ['except' => ['create', 'edit']]);
+  });

 

ルートが反映されているかを確認

laravel $ docker-compose exec php-fpm php artisan route:list

+--------+-----------+------------------------+------------------+-----------------------------------------------------+------------+
| Domain | Method    | URI                    | Name             | Action                                              | Middleware |
+--------+-----------+------------------------+------------------+-----------------------------------------------------+------------+
|        | GET|HEAD  | /                      |                  | Closure                                             | web        |
|        | GET|HEAD  | api/articles           | articles.index   | App\Http\Controllers\Api\ArticlesController@index   | api        |
|        | POST      | api/articles           | articles.store   | App\Http\Controllers\Api\ArticlesController@store   | api        |
|        | GET|HEAD  | api/articles/{article} | articles.show    | App\Http\Controllers\Api\ArticlesController@show    | api        |
|        | PUT|PATCH | api/articles/{article} | articles.update  | App\Http\Controllers\Api\ArticlesController@update  | api        |
|        | DELETE    | api/articles/{article} | articles.destroy | App\Http\Controllers\Api\ArticlesController@destroy | api        |
+--------+-----------+------------------------+------------------+-----------------------------------------------------+------------+

 

シーダファイル作成

$ docker-compose exec php-fpm php artisan make:seeder ArticlesTableSeeder

 

database/seeds/ArticlesTableSeeder.php

database/seeds/ArticlesTableSeeder.php

<?php

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class ArticlesTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('articles')->insert([
            'title' => 'Laravel入門',
            'body'  => 'わかりやすい',
            'created_at' => new DateTime(),
            'updated_at' => new DateTime(),
        ]);
        DB::table('articles')->insert([
            'title' => 'Laravel実践開発',
            'body'  => '実践的な内容',
            'created_at' => new DateTime(),
            'updated_at' => new DateTime(),
        ]);
        DB::table('articles')->insert([
            'title' => 'SQLの苦手を克服する本',
            'body'  => '1章がとても良い。',
            'created_at' => new DateTime(),
            'updated_at' => new DateTime(),
        ]);
    }
}

 

 

 

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        // $this->call(UsersTableSeeder::class);
+       $this->call(ArticlesTableSeeder::class);
    }
}

 

マイグレーション、シーディング

$ docker-compose exec php-fpm php artisan migrate --seed

 

 

Postmanで動作確認する

 

一覧表示

 

 

idを選択して表示

 

idを指定して更新

 

idを指定して削除

 

 

 

 

 

 

[amazon_link asins=’4798052582,4798059072,4802611846′ template=’ProductCarousel’ store=’izayoi55-22′ marketplace=’JP’ link_id=’15dae743-56c1-4c7d-8d93-44d85be92651′]

 

 

@see

 

Amazonおすすめ

iPad 9世代 2021年最新作

iPad 9世代出たから買い替え。安いぞ!🐱 初めてならiPad。Kindleを外で見るならiPad mini。ほとんどの人には通常のiPadをおすすめします><

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)