リソースの作成、読み取り、更新、および削除は、ほとんどすべてのアプリケーションで使用されます。 Laravelは、リソースコントローラーを使用してプロセスを簡単にするのに役立ちます。 リソースコントローラーは、作業をはるかに楽にし、いくつかのクールなLaravelルーティング技術を利用します。 今日は、リソースコントローラーを使用して完全に機能するCRUDアプリケーションを取得するために必要な手順を実行します。

このチュートリアルでは、リソースを作成、読み取り、更新、および削除(CRUD)するための管理パネルを用意するプロセスを実行します。 例としてサメを使用してみましょう。 EloquentORMも利用します。

このチュートリアルでは、次の手順について説明します。

  • データベースとモデルの設定
  • リソースコントローラーとそのルートの作成
  • 必要なビューの作成
  • リソースコントローラーの各メソッドの説明

開始するには、コントローラールート、およびビューファイルが必要です。

このチュートリアルで説明されているすべてのコードのリポジトリをGitHubで表示および複製できます。

データベースの準備

サメの移動

CRUDのすべての機能を実行できるように、クイックデータベースを設定する必要があります。 Laravelアプリケーションのルートディレクトリにあるコマンドラインで、移行を作成しましょう。

  1. php artisan make:migration create_sharks_table --table=sharks --create

これにより、app/database/migrationsでサメの移動が作成されます。 そのファイルを開き、name、email、およびshark_levelフィールドを追加しましょう。

app / database / migrations / #### _ ## _ ## _ ###### _ create_sharks_table.php
<?php

use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreatesharksTable extends Migration {

    /**
        * Run the migrations.
        *
        * @return void
        */
    public function up()
    {
        Schema::create('sharks', function(Blueprint $table)
        {
            $table->increments('id');

            $table->string('name', 255);
            $table->string('email', 255);
            $table->integer('shark_level');

            $table->timestamps();
        });
    }

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

}

もう一度コマンドラインから、この移行を実行してみましょう。 データベース設定app/config/database.phpで適切であることを確認してから、次を実行します。

php artisan migrateデータベースに、CRUD(作成、読み取り、更新、削除)するすべてのサメを収容するサメテーブルが追加されました。 移行の詳細については、Laravelドキュメントをご覧ください。

サメの雄弁なモデル

データベースができたので、データベース内のサメに簡単にアクセスできるように、単純なEloquentモデルを作成しましょう。 Eloquent ORM について読んで、独自のアプリケーションでどのように使用できるかを確認できます。

app/modelsフォルダーに、shark.phpモデルを作成しましょう。

app / models / shark.php

<?php

    class shark extends Eloquent
    {

    }

それでおしまい! Eloquentは残りを処理できます。 デフォルトでは、このモデルはsharksテーブルにリンクし、後でコントローラーでアクセスできます。

コントローラの作成

Laravelの公式ドキュメントから、リソースコントローラーで、職人ツールを使用してリソースコントローラーを生成できます。

先に進んでそれをしましょう。 これは簡単な部分です。 Laravelプロジェクトのルートディレクトリにあるコマンドラインから、次のように入力します。

php artisan make:controller sharkController --resourceこれにより、必要なすべてのメソッドを備えたリソースコントローラーが作成されます。

app / controllers / sharkController.php
<?php

class sharkController extends BaseController {

    /**
        * Display a listing of the resource.
        *
        * @return Response
        */
    public function index()
    {
        //
    }

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

    /**
        * Store a newly created resource in storage.
        *
        * @return Response
        */
    public function store()
    {
        //
    }

    /**
        * Display the specified resource.
        *
        * @param  int  $id
        * @return Response
        */
    public function show($id)
    {
        //
    }

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

    /**
        * Update the specified resource in storage.
        *
        * @param  int  $id
        * @return Response
        */
    public function update($id)
    {
        //
    }

    /**
        * Remove the specified resource from storage.
        *
        * @param  int  $id
        * @return Response
        */
    public function destroy($id)
    {
        //
    }

}

ルートの設定

コントローラを生成したので、アプリケーションにそれを使用するために必要なルートがあることを確認しましょう。 これはもう1つの簡単な部分です(実際にはすべて簡単な部分である可能性があります)。 routers.php ファイルに、次の行を追加します。

app / routers.php
<?php

    Route::resource('sharks', 'sharkController');

これにより、そのリソースコントローラーに多くのアクションが自動的に割り当てられます。 ここで、ブラウザに移動してexample.com/sharksでアプリケーションを表示すると、sharkControllerの適切なメソッドに対応します。

コントローラによって処理されるアクション

HTTP動詞 パス(URL) アクション(方法) ルート名
得る /サメ 索引 sharks.index
得る / sharks / create 作成 sharks.create
役職 /サメ お店 sharks.store
得る / sharks / {id} 公演 sharks.show
得る / sharks /{id}/編集 編集 sharks.edit
PUT / PATCH / sharks / {id} アップデート sharks.update
消去 / sharks / {id} 破壊する sharks.destroy

ヒント:コマンドラインからphp artisan routesを実行して、アプリケーションに関連付けられているすべてのルートを確認できます。

ビュー

ルートのうち4つだけがGETルートであるため、必要なビューは4つだけです。 app/viewsフォルダーで、これらのビューを作成しましょう。

app
└───views
    └───sharks
        │    index.blade.php
        │    create.blade.php
        │    show.blade.php
        │    edit.blade.php

すべてを連携させる

これで、移行、データベース、モデルコントローラーとルートビューができました。 これらすべてを連携させて、アプリケーションを構築しましょう。 リソースコントローラーで作成されたメソッドを1つずつ確認し、すべてが機能するようにします。

すべてのリソースを表示するsharks.index

説明 URL コントローラ機能 ファイルを閲覧する
すべてのサメを表示するためのデフォルトページ。 GET example.com/sharks 索引() app / views / sharks / index.blade.php

コントローラ関数index()

この関数では、すべてのサメを取得してビューに渡します。

app / controllers / sharkController.php

<?php

...

    /**
        * Display a listing of the resource.
        *
        * @return Response
        */
    public function index()
    {
        // get all the sharks
        $sharks = shark::all();

        // load the view and pass the sharks
        return View::make('sharks.index')
            ->with('sharks', $sharks);
    }
...

ビューapp/views / sharks / index.blade.php

次に、サメをループしてテーブルに表示するビューを作成しましょう。 サイトにTwitterBootstrap を使用するのが好きなので、テーブルではこれらのクラスを使用します。

app / views / sharks / index.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Shark App</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
</head>
<body>
<div class="container">

<nav class="navbar navbar-inverse">
    <div class="navbar-header">
        <a class="navbar-brand" href="{{ URL::to('sharks') }}">shark Alert</a>
    </div>
    <ul class="nav navbar-nav">
        <li><a href="{{ URL::to('sharks') }}">View All sharks</a></li>
        <li><a href="{{ URL::to('sharks/create') }}">Create a shark</a>
    </ul>
</nav>

<h1>All the sharks</h1>

<!-- will be used to show any messages -->
@if (Session::has('message'))
    <div class="alert alert-info">{{ Session::get('message') }}</div>
@endif

<table class="table table-striped table-bordered">
    <thead>
        <tr>
            <td>ID</td>
            <td>Name</td>
            <td>Email</td>
            <td>shark Level</td>
            <td>Actions</td>
        </tr>
    </thead>
    <tbody>
    @foreach($sharks as $key => $value)
        <tr>
            <td>{{ $value->id }}</td>
            <td>{{ $value->name }}</td>
            <td>{{ $value->email }}</td>
            <td>{{ $value->shark_level }}</td>

            <!-- we will also add show, edit, and delete buttons -->
            <td>

                <!-- delete the shark (uses the destroy method DESTROY /sharks/{id} -->
                <!-- we will add this later since its a little more complicated than the other two buttons -->

                <!-- show the shark (uses the show method found at GET /sharks/{id} -->
                <a class="btn btn-small btn-success" href="{{ URL::to('sharks/' . $value->id) }}">Show this shark</a>

                <!-- edit this shark (uses the edit method found at GET /sharks/{id}/edit -->
                <a class="btn btn-small btn-info" href="{{ URL::to('sharks/' . $value->id . '/edit') }}">Edit this shark</a>

            </td>
        </tr>
    @endforeach
    </tbody>
</table>

</div>
</body>
</html>

これで、すべてのサメを1ページに表示できます。 データベースを作成したり、サメをシードしたりしていないため、現在表示されるものはありません。 フォームに移動してサメを作成しましょう。

index-blade

新しいリソースの作成sharks.create

説明 URL コントローラ機能 ファイルを閲覧する
フォームを表示して、新しいサメを作成します。 GET example.com/sharks/create 作成() app / views / sharks / create.blade.php

コントローラ関数create()

この関数では、新しいサメを作成するためのフォームを表示します。 このフォームはstore()メソッドで処理されます。

app / controllers / sharkController.php
<?php
...
    /**
        * Show the form for creating a new resource.
        *
        * @return Response
        */
    public function create()
    {
        // load the create form (app/views/sharks/create.blade.php)
        return View::make('sharks.create');
    }
...

ビューapp/views / sharks / create.blade.php

app / views / sharks / create.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Shark App</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
</head>
<body>
<div class="container">

<nav class="navbar navbar-inverse">
    <div class="navbar-header">
        <a class="navbar-brand" href="{{ URL::to('sharks') }}">shark Alert</a>
    </div>
    <ul class="nav navbar-nav">
        <li><a href="{{ URL::to('sharks') }}">View All sharks</a></li>
        <li><a href="{{ URL::to('sharks/create') }}">Create a shark</a>
    </ul>
</nav>

<h1>Create a shark</h1>

<!-- if there are creation errors, they will show here -->
{{ HTML::ul($errors->all()) }}

{{ Form::open(array('url' => 'sharks')) }}

    <div class="form-group">
        {{ Form::label('name', 'Name') }}
        {{ Form::text('name', Input::old('name'), array('class' => 'form-control')) }}
    </div>

    <div class="form-group">
        {{ Form::label('email', 'Email') }}
        {{ Form::email('email', Input::old('email'), array('class' => 'form-control')) }}
    </div>

    <div class="form-group">
        {{ Form::label('shark_level', 'shark Level') }}
        {{ Form::select('shark_level', array('0' => 'Select a Level', '1' => 'Sees Sunlight', '2' => 'Foosball Fanatic', '3' => 'Basement Dweller'), Input::old('shark_level'), array('class' => 'form-control')) }}
    </div>

    {{ Form::submit('Create the shark!', array('class' => 'btn btn-primary')) }}

{{ Form::close() }}

</div>
</body>
</html>

リソースをstore()しようとしたときの検証エラーを示すために、上記のエラーセクションを追加します。 <$>[注] ヒント: 使用する場合{{ Form::open() }} 、Laravelは、クロスサイトリクエストフォージェリから保護するために、トークンを使用して非表示の入力フィールドを自動的に作成します。 詳細については、Laravelドキュメントをご覧ください。 <$>

これでフォームができましたが、送信ボタンが押されたときに何かを実行する必要があります。 このフォームのactionexample.com/sharksへのPOSTに設定しました。 リソースコントローラーはこれを処理し、リクエストをstore()メソッドに自動的にルーティングします。 今それを処理しましょう。

リソースストアの保存()

説明 URL コントローラ機能 ファイルを閲覧する
作成フォームの送信を処理し、サメをデータベースに保存します。 POST example.com/sharks お店() 無し

フォームアクションとURLからわかるように、サメを保存するためにURLに余分なものを渡す必要はありません。 このフォームはPOSTメソッドを使用して送信されるため、フォーム入力はリソースの保存に使用されるデータになります。

フォームを処理するには、入力を検証エラーメッセージが存在する場合は返送データベースに対して認証ストアすべてが良ければリソース。 飛び込みましょう。

コントローラ関数store()

app / controllers / sharkController.php
<?php
...
    /**
        * Store a newly created resource in storage.
        *
        * @return Response
        */
    public function store()
    {
        // validate
        // read more on validation at http://laravel.com/docs/validation
        $rules = array(
            'name'       => 'required',
            'email'      => 'required|email',
            'shark_level' => 'required|numeric'
        );
        $validator = Validator::make(Input::all(), $rules);

        // process the login
        if ($validator->fails()) {
            return Redirect::to('sharks/create')
                ->withErrors($validator)
                ->withInput(Input::except('password'));
        } else {
            // store
            $shark = new shark;
            $shark->name       = Input::get('name');
            $shark->email      = Input::get('email');
            $shark->shark_level = Input::get('shark_level');
            $shark->save();

            // redirect
            Session::flash('message', 'Successfully created shark!');
            return Redirect::to('sharks');
        }
    }
...

フォームの処理中にエラーが発生した場合は、それらのエラーを含む作成フォームにリダイレクトします。 ユーザーが何が悪かったのかを理解できるように、それらを追加します。 これらは、前に設定したエラーセクションに表示されます。

これで、サメを作成してメインページに表示できるようになります。 example.com/sharksに移動すると、そこにあります。 残っているのは、単一のサメ更新、および削除を表示することだけです。

created

リソースの表示show()

説明 URL コントローラ機能 ファイルを閲覧する
サメの1人を見せてください。 GET example.com/sharks/ {id} 公演() app / views / sharks / show.blade.php

コントローラ関数show()

app / controllers / sharkController.php
<?php

...

    /**
        * Display the specified resource.
        *
        * @param  int  $id
        * @return Response
        */
    public function show($id)
    {
        // get the shark
        $shark = shark::find($id);

        // show the view and pass the shark to it
        return View::make('sharks.show')
            ->with('shark', $shark);
    }

...

ビューapp/views / sharks / show.blade.php

app / views / sharks / show.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Shark App</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
</head>
<body>
<div class="container">

<nav class="navbar navbar-inverse">
    <div class="navbar-header">
        <a class="navbar-brand" href="{{ URL::to('sharks') }}">shark Alert</a>
    </div>
    <ul class="nav navbar-nav">
        <li><a href="{{ URL::to('sharks') }}">View All sharks</a></li>
        <li><a href="{{ URL::to('sharks/create') }}">Create a shark</a>
    </ul>
</nav>

<h1>Showing {{ $shark->name }}</h1>

    <div class="jumbotron text-center">
        <h2>{{ $shark->name }}</h2>
        <p>
            <strong>Email:</strong> {{ $shark->email }}<br>
            <strong>Level:</strong> {{ $shark->shark_level }}
        </p>
    </div>

</div>
</body>
</html>

show

リソースの編集edit()

説明 URL コントローラ機能 ファイルを閲覧する
データベースからサメを引き出し、編集できるようにします。 GET example.com/sharks/ {id} / edit 編集() app / views / sharks / edit.blade.php

サメを編集するには、データベースからサメをプルし、作成フォームを表示する必要がありますが、選択したサメの情報を入力します。 生活を楽にするために、フォームモデルバインディングを使用します。 これにより、モデルから情報を取得して、フォームの入力フィールドにバインドできます。 編集フォームへの入力が簡単になります。これらのフォームがかなり大きくなり始めると、作業がはるかに楽になります。

コントローラ関数edit()

app / controllers / sharkController.php

<?php

...

    /**
        * Show the form for editing the specified resource.
        *
        * @param  int  $id
        * @return Response
        */
    public function edit($id)
    {
        // get the shark
        $shark = shark::find($id);

        // show the edit form and pass the shark
        return View::make('sharks.edit')
            ->with('shark', $shark);
    }
...

ビューapp/views / sharks / edit.blade.php

app / views / sharks / edit.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Shark App</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
</head>
<body>
<div class="container">

<nav class="navbar navbar-inverse">
    <div class="navbar-header">
        <a class="navbar-brand" href="{{ URL::to('sharks') }}">shark Alert</a>
    </div>
    <ul class="nav navbar-nav">
        <li><a href="{{ URL::to('sharks') }}">View All sharks</a></li>
        <li><a href="{{ URL::to('sharks/create') }}">Create a shark</a>
    </ul>
</nav>

<h1>Edit {{ $shark->name }}</h1>

<!-- if there are creation errors, they will show here -->
{{ HTML::ul($errors->all()) }}

{{ Form::model($shark, array('route' => array('sharks.update', $shark->id), 'method' => 'PUT')) }}

    <div class="form-group">
        {{ Form::label('name', 'Name') }}
        {{ Form::text('name', null, array('class' => 'form-control')) }}
    </div>

    <div class="form-group">
        {{ Form::label('email', 'Email') }}
        {{ Form::email('email', null, array('class' => 'form-control')) }}
    </div>

    <div class="form-group">
        {{ Form::label('shark_level', 'shark Level') }}
        {{ Form::select('shark_level', array('0' => 'Select a Level', '1' => 'Sees Sunlight', '2' => 'Foosball Fanatic', '3' => 'Basement Dweller'), null, array('class' => 'form-control')) }}
    </div>

    {{ Form::submit('Edit the shark!', array('class' => 'btn btn-primary')) }}

{{ Form::close() }}

</div>
</body>
</html>

Laravelがコントローラーに正しくルーティングする方法を知るために、PUTのメソッドを渡す必要があることに注意してください。

リソースの更新update()

説明 URL コントローラ機能 ファイルを閲覧する
作成フォームの送信を処理し、サメをデータベースに保存します。 PUT example.com/sharks アップデート() 無し

このコントローラーメソッドは、編集フォームを処理します。 store()と非常によく似ています。 検証更新、およびリダイレクトします。

コントローラ関数update()

app / controllers / sharkController.php

<?php

...

    /**
        * Update the specified resource in storage.
        *
        * @param  int  $id
        * @return Response
        */
    public function update($id)
    {
        // validate
        // read more on validation at http://laravel.com/docs/validation
        $rules = array(
            'name'       => 'required',
            'email'      => 'required|email',
            'shark_level' => 'required|numeric'
        );
        $validator = Validator::make(Input::all(), $rules);

        // process the login
        if ($validator->fails()) {
            return Redirect::to('sharks/' . $id . '/edit')
                ->withErrors($validator)
                ->withInput(Input::except('password'));
        } else {
            // store
            $shark = shark::find($id);
            $shark->name       = Input::get('name');
            $shark->email      = Input::get('email');
            $shark->shark_level = Input::get('shark_level');
            $shark->save();

            // redirect
            Session::flash('message', 'Successfully updated shark!');
            return Redirect::to('sharks');
        }
    }
...

リソースの削除destroy()

説明 URL コントローラ機能 ファイルを閲覧する
作成フォームの送信を処理し、サメをデータベースに保存します。 削除example.com/sharks/{id} 破壊する() 無し

このためのワークフローは、ユーザーがすべてのサメを表示し、削除ボタンを表示し、それをクリックして削除するというものです。 app/views/sharks/index.blade.phpで削除ボタンを作成したことはないので、ここで作成します。 また、成功メッセージを表示する通知セクションを追加します。

DELETE HTTP動詞を使用してアプリケーションにリクエストを送信する必要があるため、ボタンでは機能しないため、これを行うためのフォームを作成します。

Alert: DELETE HTTP動詞は、sharks.destroyルートにアクセスするときに使用されます。 method DELETEを使用してボタンやフォームを作成することはできないため、削除フォームに非表示の入力フィールドを作成して、それを偽装する必要があります。

ビューapp/views / sharks / index.blade.php

app / views / sharks / index.blade.php

...

    @foreach($sharks as $key => $value)
        <tr>
            <td>{{ $value->id }}</td>
            <td>{{ $value->name }}</td>
            <td>{{ $value->email }}</td>
            <td>{{ $value->shark_level }}</td>

            <!-- we will also add show, edit, and delete buttons -->
            <td>

                <!-- delete the shark (uses the destroy method DESTROY /sharks/{id} -->
                <!-- we will add this later since its a little more complicated than the other two buttons -->
                {{ Form::open(array('url' => 'sharks/' . $value->id, 'class' => 'pull-right')) }}
                    {{ Form::hidden('_method', 'DELETE') }}
                    {{ Form::submit('Delete this shark', array('class' => 'btn btn-warning')) }}
                {{ Form::close() }}

                <!-- show the shark (uses the show method found at GET /sharks/{id} -->
                <a class="btn btn-small btn-success" href="{{ URL::to('sharks/' . $value->id) }}">Show this shark</a>

                <!-- edit this shark (uses the edit method found at GET /sharks/{id}/edit -->
                <a class="btn btn-small btn-info" href="{{ URL::to('sharks/' . $value->id . '/edit') }}">Edit this shark</a>

            </td>
        </tr>
    @endforeach
    ...

そのフォーム送信ボタンをクリックすると、Laravelはsharks.destroyルートを使用し、コントローラーでそれを処理できます。

コントローラ関数destroy()

app / controllers / sharkController.php
<?php

...

    /**
        * Remove the specified resource from storage.
        *
        * @param  int  $id
        * @return Response
        */
    public function destroy($id)
    {
        // delete
        $shark = shark::find($id);
        $shark->delete();

        // redirect
        Session::flash('message', 'Successfully deleted the shark!');
        return Redirect::to('sharks');
    }
...

結論

それがすべてです! あらゆる種類のシナリオでリソースコントローラーをどのように使用できるかを理解できるように、十分に説明したことを願っています。 コントローラを作成し、routesファイルに1行を作成するだけで、CRUDを実行するための基盤が整います。

いつものように、質問やコメントがあればお知らせください。 今後の記事でLaravelについてさらに詳しく説明しますので、具体的なことがあれば、コメントに入れるか、メールでお問い合わせください。

参考資料:Laravelの詳細については、SimpleLaravelシリーズをご覧ください。