Polymorphic many to many relation(morphToMany)

The last of laravel database relation.

$ php artisan make:model Post -m
$ php artisan make:model Video -m
$ php artisan make:model Tags -m

Schema::create('videos', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });

$ php artisan make:model Taggable -m

Schema::create('taggables', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('tag_id');
            $table->integer('taggable_id');
            $table->string('taggable_type');
            $table->timestamps();
        });

$ php artisan migrate

Post.php, Video.php

    protected $fillable = ['name'];
    public function tags(){
    	return $this->norphToMany('App\Tags', 'taggable');
    }

Tags.php

class Tags extends Model
{
    protected $fillable = ['name'];
}

insert into tags (name) values (‘php’);
insert into tags (name) values (‘ruby’);
model name間違えた。。
alter table taggables change column tag_id tags_id int;

Route::get('/create', function(){

	$post = Post::create(['name'=>'my frist post']);
	$tag1 = Tags::findOrFail(1);
	$post->tags()->save($tag1);

	$video = Video::create(['name'=>'video.now']);
	$tag2 = Tags::findOrFail(2);
	$video->tags()->save($tag2);

});

read

Route::get('/read', function(){

	$post = Post::findOrFail(9);
	foreach($post->tags as $tag){
		echo $tag;
	}
});

update

Route::get('/update', function(){

	$post = Post::findOrFail(9);
	foreach($post->tags as $tag){
		$tag->whereId(1)->update(['name'=>'google']);
	}
});

delete

Route::get('/delete', function(){

	$post = Post::find(1);

	foreach($post->tags as $tag){
		$tag->whereId(1)->delete();
	}
});