LoginSignup
14
9

More than 3 years have passed since last update.

Laravelのモデル結合ルート【暗黙の結合】を使ってみる

Posted at

暗黙の結合とは

暗黙結合とはLaravelのルートURIセグメント名と一致するEloquentモデルを
勝手に紐付けてくれる機能です
また、入力されたセグメントと一致するモデルが存在しない場合は404が返ってきます

この説明だけではパッとしないと思いますが
とても便利な機能なので是非積極的に使っていきたい機能だと思い
私も調べて試してみたので記事にしてみました

準備

まずはデフォルトのUsersテーブルを作成します

$ php artisan migrate

シーダファイルを用意してUsersテーブルに値を用意しておきます

$ php artisan make:seeder UserSeeder

作成されたシーダファイルに記述します

UserSeeder.php
<?php

use Illuminate\Database\Seeder;

class PersonTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $param = [
            'name' => '太郎',
            'email' => 'taro@gmail.com',
            'password' => '99999999'
        ];

        DB::table('users')->insert($param);

        $param = [
            'name' => '花子',
            'email' => 'hanako@gmail.com',
            'password' => '99999999'
        ];

        DB::table('users')->insert($param);

        $param = [
            'name' => '次郎',
            'email' => 'ziro@gmail.com',
            'password' => '99999999'
        ];

        DB::table('users')->insert($param);
    }
}

作成したシーダファイルを実行します

$ php artisan db:seed

3件のダミーデータを用意しておきました

次に今回所得したデータを表示するviweを作成します
resourcesmainフォルダを作成しその中にindex.blade.phpを作成してください
中身はこんな感じにしておきます

index.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>ユーザー表示</title>
</head>
<body>
    {{ $user->name }}
</body>
</html>

コントローラーを作成します

$ php artisan make:controller MainController

ここまでは準備です
では実際に暗黙結合でUsersのデータを所得して表示してみます

実際に試す

ルート定義していきます

web.php
Route::get('/users/{user}', 'MainController@index');

コントローラーを修正します

MainController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;

class MainController extends Controller
{
    public function index(User $user)
    {
        return view('main.index', compact('user'));
    }
}

これで実際に/users/1とURLを叩いてみてください
ブラウザには太郎と表示されるかと思います
これが、暗黙に結合された結果です

ルートセグメントで/users/{user}としてEloquentモデルのUserと紐づけています
{user}に入ってきた数字がUserモデルのidと合致するものが結合されます
そのモデルがコントローラーのpublic function index(User $user ){この部分の引数に渡されています
暗黙の結合があることで、仮にそのUserの情報を所得したりしたい場合に
User::find($id)みたいなことを書くことなくそのまま受け取れるのでとてもスマートで
便利な機能だなと思いました

おまけ

今回の場合はすでにあるUserモデルに新たにコントローラーを作成して利用しましたが
Userモデルのリソースコントローラーを作成することも多くあるかと思います
その際にこのコマンドを実行しコントローラーを作成することで
暗黙の結合を行うのに楽に実装できるリソースコントローラーを簡単に用意できます
コマンドにて下記を実行

$ php artisan make:controller UserController --model=User

これでUserのリソースコントローラーで下記のようにいい感じに作成してくれます

UserController.php
<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;

class UserController 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  \App\User  $user
     * @return \Illuminate\Http\Response
     */
    public function show(User $user)
    {
        //
    }

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

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\User  $user
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, User $user)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\User  $user
     * @return \Illuminate\Http\Response
     */
    public function destroy(User $user)
    {
        //
    }
}

アクションの引数には予め、指定してUserモデルが指定されていますね
これでこのリソースコントローラーもそのまま使うだけで、暗黙結合したものが利用できとても便利な機能です

今後はもっとこの機能を活用していこうと思います

14
9
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
14
9