Laravel 8.* + Backpack + CRUD- Article with tags
In order to proceed you should have:
- Laravel installed + Backpack admin (teaching purposes)
- Tags CRUD created
- virtual host ready for you
- xampp setup or other web server
- composer installed
We will define what an Article consists of
- title — text
- content — text — RichTextEditor
- tags (many available) — select with multiple options
New tutorial to add file upload to the artilce
- image (one image) — image upload
# STEP 1. create migration for many to many
php artisan make:migration:schema create_article_tags_table --model=0 --schema="article_id:integer:unsigned,tag_id:integer:unsigned"
This will create a new file in your migrations folder:
Remove the timestamp from the migration and then run:
php artisan migrate
We have now the table prepared many to many connections
#Step 2 — create article table
php artisan make:migration:schema create_articles_table --model=0 --schema="title:string,content:longText"
and then
php artisan migrate
#Step 3 — Create crud for Articles
php artisan backpack:crud article
#Step 4 — edit Article model
Add the following function
public function tags()
{
return $this->belongsToMany(Tag::class, 'article_tags','article_id', 'tag_id');
}
This makes the connection between articles and tags stating that one article could belong to many tags using the article_tags table for the reference.
Reference will be made by adding a new row for every tag.
#Step 5 — Alter Article controller
Add new function to the controller
private function getFieldsData($show = FALSE) {
return [
[
'name'=> 'title',
'label' => 'Title',
'type'=> 'text'
],
[
'name' => 'content',
'label' => 'Content',
'type' => ($show ? "textarea": 'ckeditor'),
],
[ // Select2Multiple = n-n relationship (with pivot table)
'label' => "Tags",
'type' => ($show ? "select": 'select2_multiple'),
'name' => 'tags', // the method that defines the relationship in your Model// optional
'entity' => 'tags', // the method that defines the relationship in your Model
'model' => "App\Models\Tag", // foreign key model
'attribute' => 'name', // foreign key attribute that is shown to user
'pivot' => true, // on create&update, do you need to add/delete pivot table entries?
]
];
}
Update setup method
Add new method at the bottom of the file — setupShowOperation
protected function setupShowOperation()
{
// by default the Show operation will try to show all columns in the db table,
// but we can easily take over, and have full control of what columns are shown,
// by changing this config for the Show operation
$this->crud->set('show.setFromDb', false);
$this->crud->addColumns($this->getFieldsData(TRUE));
}
Final result: