Create 4 models, Post, Video, Tag, and Taggable
php artisan make:model Post -m
php artisan make:model Video -m
php artisan make:model Tag -m
php artisan make:model Taggable -m
In our migrations
create_posts_table, create_videos_table and create_tags_table.php:
$table->string('name');
create_taggables_table:
$table->integer('tag_id');
$table->integer('taggable_id');
$table->string('taggable_type');
Now you can migrate it:
php artisan migrate
Update Models
Tag:
protected $fillable = [
'name',
];
Taggable:
protected $fillable = [
'name',
];
public function taggable(){
return $this->morphTo();
}
Post and Video:
protected $fillable = [
'name',
];
public function tags(){
$this->morphToMany('App\Models\Tag', 'taggable');
}
Create a few staff members and products in the database.
Different CRUD statements to add to routes:
Route::get('/create', function () {
$post = Post::create(['name'=>'My first post']);
$tag1 = Tag::find(1);
$post->tags()->save($tag1);
$video = Video::create(['name'=>'video.mov']);
$tag2 = Tag::find(2);
$video->tags()->save($tag2);
});
Route::get('/read', function () {
$post = Post::findOrFail(4);
foreach($post->tags as $tag){
echo $tag;
}
});
Route::get('/update', function () {
$post = Post::findOrFail(4);
foreach($post->tags as $tag){
return $tag->whereName('php')->update(['name'=>'updated php']);
}
});
Route::get('/update2', function () {
$post = Post::findOrFail(4);
$tag = Tag::find(4);
$post->tags()->save($tag);
});
Route::get('/attach', function () {
$post = Post::findOrFail(4);
$tag = Tag::find(2);
$post->tags()->attach($tag);
});
Route::get('/sync', function () {
$post = Post::findOrFail(4);
$tag = Tag::find(2);
$post->tags()->sync([1,2]);
});
Route::get('/delete', function () {
$post = Post::findOrFail(4);
foreach($post->tags as $tag){
$tag->whereId(2)->delete();
}
});