LoginSignup
13
6

More than 3 years have passed since last update.

Laravel RestAPIの作成方法

Last updated at Posted at 2020-07-22

Laravelとは

一言で言うと 「PHPのMVCアプリケーションフレームワーク」 です。
Laravel(ララベル)は、フルスタックなPHPフレームワークで、ルーティング、コントローラ、ビュー、ORMなど基本的な機能を備え、
さらに近代的なWebアプリで活用されるジョブキューやWebストレージなども積極的に統合されています。

フレームワークとは

「枠組み」・「骨組み」「構造」などといった意味があり、土台となるフレームワークに必要な機能を追加し、アプリケーションの開発を進めていくのが一般的といわれています。さまざまなシステム開発を効率化してくれる機能群ですね。
機能群だけでなく、ソフトウェアの骨組みまで用意してくれているため、少ないコードで意図する機能やデザイもが実現できます。
それぞれのフレームワーク特有の書き方を学ぶ必要はあるが、プログラミングのビギナーにとって、とてもありがたいです。

MVCとは

MVCとは「Mode」・「View」・「Controller」の略で、処理を3つの役割に分割して実装する手法です。

Modelは処理のメインロジックやデータアクセスを担当します。
Viewは処理結果として画面表示(HTML出力)を担当します。
そしてControllerはクライアントよりのリクエストを直接受け取って処理を行う、一番前面となる部分で、文字通りModelやViewを「制御」します。

RestAPI

REpresentational State Transferの略になります。
LarabelにはAPIを作成するときに、artisanコマンドを使って簡単にこのRestAPIを作成することができます。

php artisan make:controller TestController --resource

すると以下のようなControllerが作成されます。

class HogeController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \\Illuminate\\Http\\Response
     */
    public function index()
    {
        //一覧表示
    }

    /**
     * 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)
    {
        //新規作成
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \\Illuminate\\Http\\Response
     */
    public function show($id)
    {
        //レコード表示(指定のIDのやつ表示)
    }

    /**
     * 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)
    {
        //更新処理
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \\Illuminate\\Http\\Response
     */
    public function destroy($id)
    {
        //削除処理
    }
}

このままでは動かないので、ルーティングの設定もする必要があります。

Route::resource('rest','RestappController');

確認方法

php artisan route:list

表でまとめるとこんな感じになります
スクリーンショット 2020-07-22 16.56.03.png

RestAPIのMVCの使い方についての記事も自分用のメモですが記事をかきましたのでぜひ参考にしてください。
https://qiita.com/Yami_37/items/e10d25cbaa1878898396

13
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
6